javascript 将带有 jquery 的复选框添加到 div 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13036039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:41:30  来源:igfitidea点击:

Add a checkbox with jquery into a div

javascriptjqueryhtmlcheckbox

提问by dar0x

I want to add a checkbox into a div into another div (with id="#sensorList"), and then bind some event handlers to it. I do in this way

我想在一个 div 中添加一个复选框到另一个 div(带有 id="#sensorList"),然后将一些事件处理程序绑定到它。我这样做

/* Add div */
$("#sensorList").append($('<div>', { id : sensorId})
.addClass("sensorListItem")
.text(sensorId)
);

/* Adds visibile checkbox */
$("#"+sensorId).append($('<input>', { id : sensorId + "VisibleCheckbox", type:"checkbox", name: sensorId + "VisibleCheckbox"}));

It seems to work fine, but if I click on checkbox, it doesn't switch to checked status!

它似乎工作正常,但如果我单击复选框,它不会切换到选中状态!

Any idea? Thank you in advance.

任何的想法?先感谢您。



I'm so sorry, I figured out where the problem was. I was unable to see the checkbox checked because I had a click handler on div called sensorId, and I stupidly did: event.preventDefault() (there is no default behaviour clicking on a div!!!)

我很抱歉,我想出了问题所在。我无法看到复选框被选中,因为我在 div 上有一个名为 sensorId 的点击处理程序,我愚蠢地做了:event.preventDefault()(点击 div 没有默认行为!!!)

回答by kingkode

try some long hand and see if it works...

尝试一些长手,看看它是否有效......

$("#"+sensorId).append('<input type="checkbox" id="' + sensorId + 'VisibleCheckbox" name="'  + sensorId + 'VisibleCheckbox" >');

回答by Phu

It works for me. Check out the jsfiddle: http://jsfiddle.net/pVjNM/

这个对我有用。查看 jsfiddle:http: //jsfiddle.net/pVjNM/

var sensorId = "one";

/* Add div */
$("#sensorList").append($('<div>', { id : sensorId })
.addClass("sensorListItem")
.text(sensorId)
);

/* Adds visibile checkbox */
$("#"+sensorId).append($('<input>', { id : sensorId + "VisibleCheckbox", type:"checkbox", name: sensorId + "VisibleCheckbox"}));

$("input[type=checkbox]").each(function(){
    this.click();
    console.log("Should be true:", this.checked);
});


$("input[type=checkbox]").each(function(){
    this.click();
    console.log("Should be false:", this.checked);
});?