Use onmousedown to get the ID of the element you just mousedowned on?

不打扰是莪最后的温柔 提交于 2019-12-12 08:35:09

问题


Is this possible?

I am attempting to write a function for onmousedown that will return the ID of the element you just clicked for later use in recreating that element in a different div.


回答1:


You can use event delegation, to basically connect only one event handler to your entire document, and get the element which the event was originally dispatched, using event.target:

document.body.onmousedown = function (e) {
  e = e || window.event;
  var elementId = (e.target || e.srcElement).id;

  // call your re-create function
  recreate(elementId);
  // ...
}

function recreate (id) {
  // you can do the DOM manipulation here.
}

Edit: You can assign events to all your Scriptaculous draggables in this way:

Event.observe(window, 'load', function () {
  Draggables.drags.each(function (item) {
    Event.observe(item.element, 'mousedown', function () {
      alert('mouseDown ' + this.id); // the this variable is the element 
    });                              // which has been "mouse downed"
  });
});

Check an example here.




回答2:


CMS pretty much has the correct answer but you will need to make it a little more cross browser friendly.

document.body.onmousedown = function (e) {
  // Get IE event object
  e = e || window.event;
  // Get target in W3C browsers & IE
  var elementId = e.target ? e.target.id : e.srcElement.id;
  // ...
}



回答3:


If you want to replicate the div id, an easy way might be cloneNode like this:

<div id="node1">
  <span>ChildNode</span>
  <span>ChildNode</span>
</div>

<div id="container"></div>

<script type="text/javascript">
  var node1 = document.getElementById('node1');
  var node2 = node1.cloneNode(true);

  node2.setAttribute('id', 'node2');

  var container = document.getElementById('container');
  container.appendChild(node2);
</script>



回答4:


Pls insert this code to your javascript.

document.getElementById("article").onmouseup(handMu);


来源:https://stackoverflow.com/questions/1250557/use-onmousedown-to-get-the-id-of-the-element-you-just-mousedowned-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!