在 jQuery 中访问多个相同 ID 的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4789859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:56:33  来源:igfitidea点击:

Access Multiple Elements of same ID in jQuery

jqueryhtml

提问by Angel.King.47

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

在 jQuery 中我可以做这样的事情吗

$(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 myElearray number

显然每个元素都以与myEle数组编号对应的正确数字格式排序

回答by Matt Ball

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".

不要创建包含具有重复 ID 的元素的标记。这会破坏事物,并且您将比您说的更快地被迅猛龙殴打"goto"

Use classesinstead:

改用

<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

回复:OP评论

"How do i know which image is pressed?"

“我怎么知道哪个图像被按下了?”

Use the thiskeyword:

使用this关键字:

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

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

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

……我想这就是你要找的。

velociraptor

迅猛龙

回答by Cees Timmerman

If you've inherited code so horrible that you can only work with the faulty output, use jQuery("[id=theidthatshouldbeaclassinstead]")or jQuery("[id*=theidthatshouldbeaclassinstead]")if there are multiple ids for some reason.

如果您继承的代码太糟糕以至于您只能使用错误的输出,请使用jQuery("[id=theidthatshouldbeaclassinstead]")或者jQuery("[id*=theidthatshouldbeaclassinstead]")如果出于某种原因有多个 id。

回答by David

If multiple elements will share a certain property, you should assign class to them instead of id. So the resulting jquery code will look something like:

如果多个元素将共享某个属性,则应为它们分配类而不是 id。因此,生成的 jquery 代码将类似于:

$('.myEle').mouseup();

ID is to be used to uniquely identify elements.

ID 用于唯一标识元素。

回答by Dmitriy Sintsov

It is true that having multiple elements with the same idis incorrect. However it is pretty easy to generate such code in general-purpose frameworks, for example in Django one may have more than one forms in a single view with the same field auto_id. Thus it would be nice to have jQuery function which selects all of these elements so client-side Javascript code can check the length of returned list and trigger a client-side error / warning in such case.

确实,拥有多个相同的元素id是不正确的。然而,在通用框架中生成这样的代码非常容易,例如在 Django 中,一个具有相同字段的视图中可能有多个表单auto_id。因此,最好有 jQuery 函数来选择所有这些元素,以便客户端 Javascript 代码可以检查返回列表的长度并在这种情况下触发客户端错误/警告。

Also do not forget that the value of idhas to be escaped in CSS query. While recent versions of Chrome / Firefox have native support of CSS.escape(), IE may require a polyfill: https://github.com/mathiasbynens/CSS.escape

也不要忘记id在 CSS 查询中必须对的值进行转义。虽然最新版本的 Chrome / Firefox 原生支持CSS.escape(),但 IE 可能需要 polyfill:https: //github.com/mathiasbynens/CSS.escape

$.id = function(id) {
    // FF 54 generates warning when empty string is passed.
    if (typeof id !== 'string' || id === '') {
        return $();
    } else {
        // Support multiple ID's to detect content bugs.
        return $(document.querySelectorAll('#' + CSS.escape(id)))
    }
};