最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use onmousedown to get the ID of the element you just mousedowned on? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Aug 9, 2009 at 4:03 zombat 94.1k25 gold badges157 silver badges165 bronze badges asked Aug 9, 2009 at 3:57 Chris SobolewskiChris Sobolewski 12.9k13 gold badges64 silver badges96 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 16

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.

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;
  // ...
}

Pls insert this code to your javascript.

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

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>
发布评论

评论列表(0)

  1. 暂无评论