Set Label Text with JQuery

可紊 提交于 2020-01-13 08:31:30

问题


This should be quite straight forward, however the following code does not do anything as far as changing the next label's text. I have tried using .text, .html, and so on to no avail. Is there anything wrong with this code?

<script type="text/javascript">
$(document).ready(function()
{
    $("input:checkbox").on("change", checkboxChange);

    function checkboxChange()
    {
        $("#"+this.id).next("label").text("TESTTTT");
    }
});
</script>



<td width="15%" align="center"><input type="checkbox" name="task1" id="task1"></td>
<td width="25%" align="center"><label for="task1"></label></td>

回答1:


The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});



回答2:


I would just query for the for attribute instead of repetitively recursing the DOM tree.

$("input:checkbox").on("change", function() {
    $("label[for='"+this.id+"']").text("TESTTTT");
});



回答3:


You can try:

<label id ="label_id"></label>
 $("#label_id").html('value');


来源:https://stackoverflow.com/questions/20903822/set-label-text-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!