用于动态 id 的 JQuery 选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11572569/
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
JQuery Selector for dynamic id
提问by michael
I am trying to change the image source in the Jquery
我正在尝试更改 Jquery 中的图像源
<a href="" class="wanted" id="'.$status_id[$num].'"><img src="/images/wanted.png">
through a JQuery selector:
通过 JQuery 选择器:
$(".wanted "+ id).attr("src", '/images/wanted_.png');
Where id
is defined in the javascript as the php variable $status_id[$num]
. I first tried using $(this)
to no avail. Any insight would be helpful.
在id
javascript 中将where定义为 php 变量$status_id[$num]
。我第一次尝试使用$(this)
无济于事。任何见解都会有所帮助。
回答by karan k
When you access $(".wanted"+id)
, you are actually trying to access an element with the class name = wanted+id. This is because of the '.' before 'wanted'. Also, you seem to be accessing the <a>
tag directly and setting it's src
attribute. You need to access the <img>
tag.
What you could try is this:
当您访问 时$(".wanted"+id)
,您实际上是在尝试访问类名 = 想要+id 的元素。这是因为'.' 在“想要”之前。此外,您似乎<a>
直接访问标签并设置它的src
属性。您需要访问该<img>
标签。你可以尝试的是:
var x=document.getElementById(id);
$(x).find("img")[0].setAttribute("src","/images/wanted_.png");
回答by Chandu
ID of the HTML elements should be unique across the page.
HTML 元素的 ID 在整个页面中应该是唯一的。
You can try
你可以试试
//I assume id variable is already assigned the id of the element e.g var id = "<?php echo $status_id[$num] ?>";
$("#"+ id).attr("src", '/images/wanted_.png');
If you really want to select an element that has the given id and also the class wanted then try this:
如果你真的想选择一个具有给定 id 和想要的类的元素,那么试试这个:
$("#"+ id + ".wanted ").attr("src", '/images/wanted_.png');
回答by Sinetheta
Either you have access to the ID when the JS is created, or you don't. If you don't then you'll have to find another way to target the item eg: $('.wanted')
您可以在创建 JS 时访问 ID,也可以没有。如果不这样做,则必须找到另一种方法来定位该项目,例如:$('.wanted')
If you do, then put it in: $('#<?php echo $status_id[$num]; ?>')
如果你这样做,那么把它放在: $('#<?php echo $status_id[$num]; ?>')
回答by Charlie
Give it another class like imgToChange
, then use $(".imgToChange")
给它另一个类imgToChange
,然后使用$(".imgToChange")