如何使用jquery更新标签标签

How to update label tag using jquery

本文关键字:标签 更新 jquery 何使用      更新时间:2023-09-26

我有以下HTML:

<div id="myDiv">
  <table id="tbl0">
    <tr id="tr0" style="display: none;">
      <td>
        <label id="lbl0"></label>
      </td>
    </tr>
    <tr id="tr1" style="display: none;">
      <td>
        <label id="lbl1"></label>
      </td>
    </tr>
    <tr id="tr2" style="display: none;">
      <td>
        <label id="lbl2"></label>
      </td>
    </tr>
  </table>
</div>

和下面的jquery设置行为可见,并更新(但失败)一些文本标签的标签。

var myStr = $(this).text();
var myArr = myStr.split(',');
$.each(myArr, function (i) {
  // This part works just fine
  var tr = $('#myDiv').find("#tr" + i);
  tr.css('display', 'inline');
  // The label is found, but I can't get jquery to update the text of
  // ...it no matter what I try
  var lbl = tr.find("lbl" + i);
  lbl.val('hello world'); // doesn't work
  lbl.text('hello world'); // doesn't work
  lbl.html('hello world'); // doesn't work
});

我哪里做错了?

try this…

var lbl = tr.find("#lbl" + i);

您正在尝试选择<lbl1/>标记,该标记显然不存在

使用#指定要搜索的id

你是错误的标签被发现,你需要使用#来指定它是一个id:

var lbl = tr.find("#lbl" + i);
同时

:

lbl.text('hello world');
lbl.html('hello world');

是设置标签文本的正确方法,我更喜欢.html(),因为它不解析来自htmlspecialchars的字符串,它可能会稍微快一些。

错误在这一行:

var lbl = tr.find("#lbl" + i);

您忘记了#符号,因为您正在按ID查找。

我偶然发现了这个线程,虽然它帮助我在正确的方向上引导我,但一旦我通过设置标签元素上的innerHTML属性找到了我的标签,我就能够以不同的方式解决问题。我用的是jQuery。

var labels = document.getElementsByClassName('someclassname');
$(labels).each(function (index, element) {    
    element.innerHTML = 'hello world';
});
相关文章: