jQuery检索relatedTarget.data('url')值 [英] jquery retrieve relatedTarget.data('url') value
问题描述
我需要从event.relatedTarget检索data-url属性的值
I need to retrieve the value of data-url attribute from event.relatedTarget
我尝试了很多方法:
e.relatedTarget.data('url')
e.relatedTarget.attr('url')
e.relatedTarget.prop('url')
,但它总是返回错误. 但是值在那里:
but it always return an error.. but the value is there:
我如何找回它? 谢谢! 乔
how can I retrieve it? thanks! Joe
推荐答案
看到您正在直接访问事件对象本身,jQuery的attr()
和prop()
方法在这里将无法使用,因为这不是jQuery对象.您会注意到事件对象上也没有data
键,相反,该键称为dataset
.此外,这不是功能,因此()
中括号在这里将无法实现任何功能.
Seeing as you're directly accessing the event object itself, jQuery's attr()
and prop()
methods will not work here as this isn't a jQuery object. You'll notice that there is no data
key on the event object as well, instead the key is called dataset
. Furthermore, this isn't a function, so ()
brackets will not achieve anything here.
您要使用e.relatedTarget.data('url')
e.relatedTarget.dataset['url']
或者:
e.relatedTarget.dataset.url
值得注意的是,与将事件对象转换为jQuery对象并调用jQuery函数之一(此处其他答案建议)相比,此方法具有显着更好的性能,因为您拥有所有属性. jQuery所要做的就是将其转换回您已经拥有的对象,并以与我上面包含的方式非常相似的方式访问该属性,因此,与其直接从A转到B,您最终会从A转到B C然后回到A到B.
It's worth noting that this has significantly better performance than converting the event object into a jQuery object and calling one of jQuery's functions as the other answers here suggest as you have all the properties right there. All jQuery will do is convert it back into the object you already have and access the property in a very similar way to what I've included above, so rather than going directly from A to B, you'd end up going from A to C then back to A to B.
这篇关于jQuery检索relatedTarget.data('url')值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!