Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

html - Access Multiple Elements of same ID in jQuery

If i have elements such as this

<img src='0.jpg' id='images' />
<img src='...' id='myEle' />
<img src='...' id='myEle' />

in jQuery can i do something like this

$(document).ready(function() {
    $('#myEle').mouseup(function () {

        $('#images').attr("src", myEle.getNumber() + ".jpg"); 
    }
}

Obviously each element is sorted in the correct number format that corresponds to the myEle array number

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Do not create markup that contains elements with duplicate IDs. This will break things, and you will be mauled by a velociraptor faster than you can say "goto".

Use classes instead:

<img src='0.jpg' id='images' />
<img src='...' class='myEle' />
<img src='...' class='myEle' />

then...

$(document).ready(function() {
    $('.myEle').live('mouseup', function () {

        $('#images').attr("src", myEle.getNumber() + ".jpg"); 
    });
});

Re: OP comment

"How do i know which image is pressed?"

Use the this keyword:

$(document).ready(function() {
    $('.myEle').live('mouseup', function () {

        $('#images').attr("src", $(this).attr('src')); 
    });
});

...I think that's what you're looking for.

velociraptor


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...