jquery 检索相关Target.data('url') 值

Joe*_*Joe 6 jquery custom-data-attribute

我需要从 event.relatedTarget 检索 data-url 属性的值

我尝试了很多方法:

e.relatedTarget.data('url')
e.relatedTarget.attr('url')
e.relatedTarget.prop('url')
Run Code Online (Sandbox Code Playgroud)

但它总是返回一个错误..但值在那里:

截屏

我怎样才能找回它?谢谢!乔

Jam*_*lly 7

由于您直接访问事件对象本身,因此 jQueryattr()prop()方法在这里不起作用,因为它不是 jQuery 对象。您会注意到data事件对象上也没有键,而是键被称为dataset。此外,这不是一个函数,所以()括号在这里不会实现任何功能。

而不是e.relatedTarget.data('url'),你会想要使用:

e.relatedTarget.dataset['url']
Run Code Online (Sandbox Code Playgroud)

或者:

e.relatedTarget.dataset.url
Run Code Online (Sandbox Code Playgroud)

值得注意的是,这比将事件对象转换为 jQuery 对象并调用 jQuery 函数之一的性能要好得多,因为这里的其他答案建议您拥有所有属性。jQuery 所做的就是将它转换回您已经拥有的对象,并以与我上面包含的非常相似的方式访问该属性,因此与其直接从 A 转到 B,您最终会从 A 转到C然后回到A到B。


小智 5

$(e.relatedTarget).data('url');
Run Code Online (Sandbox Code Playgroud)

这是一个js元素。要使用 data() 函数,您必须将该元素设为 jquery 元素。