I am making a . 。 I am adding the dynamically via javascript and adding labels for them too. ,并为其添加标签。
Now I want but onClick attribute is not allowed in "label" tag. 但“标签”标签中不允许使用onClick属性。 So I added the text as a child of checkbox but it is not visible but the onclick event is working on checkbox.
var chked = document.createElement("input");
chked.type = 'checkbox';
chked.value = data[friendIndex].id;
chked.id = friendIndex;
chked.width = '300';
chked.onclick = function (){document.getElementById(this.id).style.backgroundColor='#4285f4';};
var label = document.createElement('label');
label.htmlFor = friendIndex;
label.id = friendIndex;
label.setAttribute('onclick' ,function (){document.getElementById(this.id).style.backgroundColor='#4285f4';});
label.appendChild(document.createTextNode(data[friendIndex].name));
chked.appendChild(document.createTextNode(data[friendIndex].name));
var mybr=document.createElement('br');
chklstTarget.appendChild(chked);
chklstTarget.appendChild(label);
chklstTarget.appendChild(mybr);
Any reason you need to do this via Javascript? You can do this using CSS only.
<input type="checkbox" />
<label>Check Me!</label>
input[type=checkbox] + label {
color: black;
}
input[type=checkbox]:checked + label {
background: red;
}
Use jquery click function to toggle the class
$("input[type=checkbox]").change(function() {
$(this).parent().toggleClass("checked");
});
How about append CheckBox to Label.
Then you can get CheckBox's onClick event from click ChkeckBox and Label area both.
And change label's color.
example)
label.appendChild( chked );
label.appendChild( textToDisplay );
chklstTarget.appendChild( label );
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.