javascript - 如何向 textfield.JS/Jquery 中具有特定文本值的 <img> 标签添加属性

标签 javascript jquery html

我有一个<img>标签附加到每个 <text>标签如下图:

<div>
  <text text-anchor="start" class="text">Text 1</text>
  <img src="abc.png" class="nv-hover-icon" height="15" width="22"/>
</div>
<div>
 <text text-anchor="start" class="text">Text 2</text>
 <img src="abc.png" class="nv-hover-icon" height="15" width="22"/>
</div>
<div>
  <text text-anchor="start" class="text">Text 3</text>
  <img src="abc.png" class="nv-hover-icon" height="15" width="22"/>
</div>

如何向文本 == 'Text2' 的图像添加属性。

if($("text.text").text() == 'Text 2'){
   //add an attr 'id' to the img tag
  //pseudo code: $("img").attr("id", "image-id");
}

关于如何实现这一目标有什么想法吗? 谢谢!!

最佳答案

试试这个:您可以使用.filter()来查找所需的文本,然后使用.next()来定位图像并添加属性

$("text.text").filter(function(){
  return $(this).text().trim() == 'Text 2';
}).next().attr("id", "image-id");

<强> API Doc for filter()

关于javascript - 如何向 textfield.JS/Jquery 中具有特定文本值的 <img> 标签添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27614887/

相关文章:

javascript - 无法在node js中使用post请求

javascript - javascript 中的 If/else 不返回未定义的 else

JavaScript 根据变量值检查字段值

javascript - 为什么这个 onmouseover 函数不起作用? -"Cannot read property ' 未定义的显示'

javascript - 显示/隐藏 div Javascript 错误

jquery - 哪些工具提示插件与 jQuery 1.5(当前版本)兼容?

javascript - Jquery 自动完成选择的值

javascript - 一页中的多个窗口用于书签

html - 将图像添加到 HTML 电子邮件

javascript - 使用 JavaScript 在 ForEach 循环中拆分数组值?