修改还包含输入的标签文本(复选框) [英] Modifying the text of a label that also contains an input (checkbox)
问题描述
我的文档中有一些元素,例如:
<div class="checkbox-inline">
<label><input id="myinputid" value="False" type="checkbox"/>mytext</label>
</div>
我可以使用以下方式访问获取文本:
$("#myinputid").parent().text();
这返回了mytext
,正如我希望的那样.那就是:
$("#myinputid").parent().text("newtext");
将我的初始元素更改为
<div class="checkbox-inline"><label>newtext</label></div>
如何在不删除输入的情况下更改文本部分?还是我必须重建它?
如果有一种更好的方式来构造我的复选框,那将是一个可以接受的选择.
(1)使用"for"属性是一种选择: (2)另一个选择是将结构重组为: 然后,您可以更改跨度的文本,而无需修改输入.根据此处允许在标签内进行跨度:是< div>在< label>内阻止正确吗? (3)以下可能是您原始HTML结构的一种可能的解决方案: I can access get the text using: This returns Changes my initial element to How can I change the text part without removing the input? Or do I have to reconstruct it? If there's a better way to structure my checkboxes to begin with, that would be an acceptable alternative. (1) Using the "for" attribute would be one option: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#Using_the_for_attribute Since the (2) Another option would be to restructure as: Then you can change the span's text without modifying the input. A span within a label is allowed according to here: Is <div> inside <label> block correct? (3) Here might be a possible solution for your original HTML structure: jQuery - setting an element's text only without removing other element (anchor) 这篇关于修改还包含输入的标签文本(复选框)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!<div class="checkbox-inline">
<label>
<span>mytext</span>
<input id="myinputid" value="False" type="checkbox">
</label>
</div>
$("#myinputid").parent().text();
mytext
as I had hoped it would. That is:$("#myinputid").parent().text("newtext");
<div class="checkbox-inline"><label>newtext</label></div>
<input>
is no longer child of the <label>
, the input won't be affected by your changes with text()
.<div class="checkbox-inline">
<label for="myinputid">mytext</label>
<input id="myinputid" value="False" type="checkbox">
</div>
<div class="checkbox-inline">
<label>
<span>mytext</span>
<input id="myinputid" value="False" type="checkbox">
</label>
</div>