You can get the identifier from the selected class, but not from the name of the click

Here is a jsfiddle for what I have tested http://jsfiddle.net/5hhRF/

there is a number 1 2 1 2 .... when u presses the last digit which is "2" it doesn't alert.

Am I missing some code for this case?

I copy the same code again.

<span class="open-option" id="option1" >1</span>
<span class="open-option" id="option2" >2</span>

<span id="open-option" class="option1" >1</span>
<span id="open-option" class="option2" >2</span>​

      

    $ (". open-option"). click (function () {                    
       var myID = $ (this) .attr ('id'); 
       alert (myID);
    });

    $ ("# open-option"). click (function () {                    
       var myClass = $ (this) .attr ('class'); 
       alert (myClass);
    });


                        In the meantime, there is no need to know about it. ”
+3


source to share


4 answers


click

the event only binds to the first element with the given identifier.



The ID on the page must be unique.

+3


source


You cannot assign the same ID to multiple items.

http://htmlhelp.com/reference/html40/attrs.html



The ID attribute uniquely identifies an element within a document. no two elements can have the same identifier value in the same document.

+3


source


jQuery

id

selector

returns an array, but only contains the 1st element in DOM

with id. So here in your codeclick handler is being applied to 1st DOM elements only

you can use contains selector

$("span[id*='open-option']").click(function(){                    
   var myClass=$(this).attr('class');
   alert(myClass);
});

      

script: http://jsfiddle.net/5hhRF/4/

+1


source


Item ids must be unique, I'm afraid, according to here . Otherwise, your code simply won't work.

0


source







All Articles