简体   繁体   English

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

[英]How to get HTML element from event in jquery?

In a jQuery function I am getting event on form's element click event. 在jQuery函数中,我在窗体的元素单击事件上获取事件。 Now I want to get its html. 现在我想得到它的HTML。 How it is possible ? 怎么可能?

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 谢谢

You can try event.target.outerHTML , however I'm not sure how well supported it is across all browsers. 您可以尝试event.target.outerHTML ,但我不确定它在所有浏览器中的支持程度如何。 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: 一个更复杂但肯定工作的解决方案是将元素包装在另一个元素中,然后获取父元素的html:

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

If your event is a click you can bind it using the click() method from jQuery. 如果您的事件是click ,则可以使用jQuery中的click()方法绑定它。 Use this to reach your element, like the code below: 使用this来访问您的元素,如下面的代码:

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

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. 以下是如何检测事件源html标记的示例。 This example assumes you have bound a list item click event of unordered list with CSS class name myUnorderedList but you want to disable the default action if an anchor tag is clicked within the list item : 此示例假定您已使用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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM