SegmentFault (www. sf. gg) is a leading developer technology community in China. We hope to provide programmers with a pure and high-quality technology exchange platform to learn, communicate and grow with developers and create an era for developers!
Reply content:
Example code: http://codepen.io/hj624608494...
The problem occurs when this points to this and always points to the object when the function is executed.
Function choose () {alert ($ (this ). data ('name'); // undefind because this of the choose function points to window} function choose2 () {$ ('# J_a '). click (function () {// this anonymous function of the click event points to the $ ('# J_a') object alert ($ (this ). data ('name') ;}} choose2 ()
This is passed in when binding events, onclick = "choose (this )"
Function choose (x ){
Alert (x. getAttribute ("data-name "))
}
$ (This). attr ('data-name ');
Get attributes-attr ()
The jQuery attr () method is used to obtain the attribute value.
$ ('# Toy'). attr ('data-name ');