如何将attr(id)添加到特定值的<文本>标签-Js/Jquery

How to add an attr (id) to a <text> tag of a specific value-Js/Jquery

本文关键字:文本 Jquery -Js 标签 attr id 添加      更新时间:2023-09-26

我有 3 个文本值,它们都具有类名作为属性。 但是,我试图仅向特定文本添加一些样式:例如

<text text-anchor="start" class="text">Text 1</text>
<text text-anchor="start" class="text">Text 2</text>
<text text-anchor="start" class="text">Text 3</text>

现在我试图在上面的第二个文本中添加一个唯一的 id。我怎样才能放一个条件来查看一个是否有特定的附加值attr('id'(,伪代码:

if($("text.text").text() == 'Text 2'){
   $("text.text").attr("id", "text-id");
}

如果我按照上述方式操作,则所有文本标签都设置了"id"。 如何将"ID"添加到一个?任何帮助表示赞赏..

使用 filter((

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

使用

$("text.text").each(function() {
  if ($(this).text() == 'Text 2') {
    $(this).attr("id", "text-id");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<text text-anchor="start" class="text">Text 1</text>
<text text-anchor="start" class="text">Text 2</text>
<text text-anchor="start" class="text">Text 3</text>

$('.text').each(function(){
    if($(this).text() == "Text 2"){
        $(this).attr('id','CustomID');
    }
});

小提琴 :: http://jsfiddle.net/hoja/9spwrxd9/