Modifying the text of a label that also contains an input (checkbox)

时光毁灭记忆、已成空白 提交于 2019-12-25 07:18:06

问题


I have some elements in my document like:

<div class="checkbox-inline">
  <label><input id="myinputid" value="False" type="checkbox"/>mytext</label>
</div>

I can access get the text using:

$("#myinputid").parent().text();

This returns mytext as I had hoped it would. That is:

$("#myinputid").parent().text("newtext");

Changes my initial element to

<div class="checkbox-inline"><label>newtext</label></div>

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:


(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 <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>

(2) Another option would be to restructure as:

<div class="checkbox-inline">
  <label>
    <span>mytext</span>
    <input id="myinputid" value="False" type="checkbox">
  </label>
</div>

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)




回答2:


You can put your text inside an element for example a span and then use the .siblings() function instead of the .parent() function.

<div class="checkbox-inline">
  <label>
    <input id="myinputid" value="False" type="checkbox">
    <span>mytext</span>
  </label>
</div>

$("#myinputid").siblings().text("newtext");


来源:https://stackoverflow.com/questions/39280882/modifying-the-text-of-a-label-that-also-contains-an-input-checkbox

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