简体   繁体   中英

How to update label tag using jquery

I have the following 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>

And the following jquery that sets a row to visible and updates (but fails) the label tag with some text.

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

});

So what am I doing wrong here?

try this...

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

You are trying to select a <lbl1/> tag, which obviously doesn't exist

use # to specify an id to search for.

You're wrong about the label being found, you need to use a # to specify that it is an id:

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

Both:

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

are correct ways to set the text of the label, I prefer .html() since it doesn't parse the string from htmlspecialchars it might be slightly faster.

The error is in this line:

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

You forgot # sign, since you are looking up by ID.

I stumbled upon this thread and while it helped lead me in the right direction I was able to solve a little different way once I found my label by setting the innerHTML property on the label element. I was using jQuery.

var labels = document.getElementsByClassName('someclassname');

$(labels).each(function (index, element) {    
    element.innerHTML = 'hello world';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM