Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

javascript - 如何使元素单击(针对整个文档)?(How to get the element clicked (for the whole document)?)

I would like to get the current element (whatever element that is) in an HTML document that I clicked.(我想在单击的HTML文档中获取当前元素(无论是哪个元素)。)

I am using:(我在用:) $(document).click(function () { alert($(this).text()); }); But very strangely, I get the text of the whole(!) document, not the clicked element.(但是非常奇怪的是,我得到了整个文档的文本,而不是单击的元素。) How to get only the element I clicked on?(如何仅获取我单击的元素?) Example(例) <body> <div class="myclass">test</div> <p>asdfasfasf</p> </body> If I click on the "test" text, I would like to be able to read the attribute with $(this).attr("myclass" ) in jQuery.(如果单击“测试”文本,我希望能够在jQuery中使用$(this).attr("myclass" )读取属性。)   ask by user1145216 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use the event.target which is the element which originally triggered the event.(您需要使用event.target ,它是最初触发事件的元素。)

The this in your example code refers to document .(您的示例代码中的this是指document 。) In jQuery, that's...(在jQuery中,就是...) $(document).click(function(event) { var text = $(event.target).text(); }); Without jQuery...(没有jQuery ...) document.addEventListener('click', function(e) { e = e || window.event; var target = e.target || e.srcElement, text = target.textContent || target.innerText; }, false); Also, ensure if you need to support < IE9 that you use attachEvent() instead of addEventListener() .(另外,请确保是否需要支持<IE9,并使用attachEvent()而不是addEventListener() 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...