javascript 如何从jquery中的事件获取HTML元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7702247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:00:26  来源:igfitidea点击:

How to get HTML element from event in jquery?

javascriptjqueryevents

提问by Student

In a jQuery function I am getting event on form's element click event. Now I want to get its html. How it is possible ?

在 jQuery 函数中,我收到了表单元素点击事件的事件。现在我想得到它的 html。怎么可能?

For Example:

例如:

function(event, ID, fileObj, response, data) {
    alert( $(event.target) );            // output: [object Object]
    alert( event.target );               // output: [object HTMLInputElement]
    alert( $(event.target).html() );     // output: (nothing)    
}

I want to get form object who's element is clicked through event

我想获取点击元素的表单对象 event

Thanks

谢谢

回答by Hyman

You can try event.target.outerHTML, however I'm not sure how well supported it is across all browsers. A more convoluted but sure to work solution would be to wrap the element in another element, then take the html of the parent element:

您可以尝试event.target.outerHTML,但是我不确定它在所有浏览器中的支持程度如何。一个更复杂但肯定可行的解决方案是将元素包装在另一个元素中,然后获取父元素的 html:

$('<div/>').html($(event.target).clone()).html();

回答by brolim

If your event is a clickyou can bind it using the click()method from jQuery. Use thisto reach your element, like the code below:

如果您的事件是 ,则click可以使用click()jQuery 中的方法绑定它。使用this以达到你的元素,如下面的代码:

$('#id').click(function(event){
  console.log($(this));
});

回答by Emil

Most elegant solution I found is to simply use the properties on the event target. Here is an example how to detect the event source html tag. This example assumes you have bound a list item click event of unordered list with CSS class name myUnorderedListbut you want to disable the default action if an anchor tag is clicked within the list item:

我发现的最优雅的解决方案是简单地使用事件目标上的属性。以下是如何检测事件源 html 标签的示例。 此示例假设您已使用 CSS 类名称myUnorderedList绑定了无序列表的列表项单击事件,但如果在列表项中单击锚标记,您希望禁用默认操作

$('ul.myUnorderedList').on('click', 'li', function(event){ 

    console.log('tagName: '+ event.target.tagName);    //output: "a"
    console.log('localName: '+ event.target.localName);//output: "a"
    console.log('nodeName: '+ event.target.nodeName);  //output: "A"

    if(event.target.tagName == 'a')
        return; // don't do anything...

    // your code if hyperlink is not clicked
});