问题
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