jquery retrieve relatedTarget.data('url') value

和自甴很熟 提交于 2019-12-13 14:05:59

问题


I need to retrieve the value of data-url attribute from event.relatedTarget

I tried in many ways:

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


回答1:


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.

Instead of e.relatedTarget.data('url'), you'll want to use:

e.relatedTarget.dataset['url']

Or:

e.relatedTarget.dataset.url

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.




回答2:


$(e.relatedTarget).data('url');

This is a js element. To use data() function, you have to make that element a jquery element.




回答3:


e.relatedTarget returns the reference to a DOM element, not a jQuery object.

So before you can call jQuery methods on it, you need to create a jQuery object from it:

$(e.relatedTarget).data(…)



来源:https://stackoverflow.com/questions/40173242/jquery-retrieve-relatedtarget-dataurl-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!