用于动态id的JQuery Selector

mic*_*ael 5 jquery

我正在尝试更改Jquery中的图像源

<a href="" class="wanted" id="'.$status_id[$num].'"><img src="/images/wanted.png">
Run Code Online (Sandbox Code Playgroud)

通过JQuery选择器:

$(".wanted "+ id).attr("src", '/images/wanted_.png');
Run Code Online (Sandbox Code Playgroud)

idjavascript中定义的地方是php变量$status_id[$num].我第一次尝试使用$(this)无济于事.任何见解都会有所帮助.

kar*_*n k 7

当您访问时$(".wanted"+id),您实际上是在尝试访问具有类名称= wanted + id的元素.这是因为'.' 在'通缉'之前.此外,您似乎<a>直接访问标记并设置其src属性.您需要访问该<img>标记.您可以尝试的是:

var x=document.getElementById(id);
$(x).find("img")[0].setAttribute("src","/images/wanted_.png");
Run Code Online (Sandbox Code Playgroud)


Cha*_*ndu 5

HTML 元素的 ID 在整个页面中应该是唯一的。

你可以试试

//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');
Run Code Online (Sandbox Code Playgroud)

如果你真的想选择一个具有给定 id 和想要的类的元素,那么试试这个:

$("#"+ id + ".wanted ").attr("src", '/images/wanted_.png');
Run Code Online (Sandbox Code Playgroud)