0

我正在尝试div#options_holder使用以下代码在其中显示和创建一些元素:

var counter = 1;

$('#choices').on("change", ":checkbox", function(e) {
    var theName = $(this).attr('name');
    var theID = $(this).attr('id');
    var isChecked = $(this).prop("checked");
    var input, button, append = "";

    $("#options_holder").show();

    input = capitalize(theName) + '<input name="input_' + theName + '[]" id="' + theID + '" value="" placeholder="' + capitalize(theName) + '" />';
    button = '<button type="button" class="add-size">Nuevo ' + capitalize(theName) + '</button>';

    append = counter === 1 ? input += button : input;

    $("#options_holder").append(append);
    counter++;

    console.log("You changed " + theName + ", with an id of " + theID + ", its checked property is: " + isChecked);
});

但它不起作用,因为div#options_holder仍然隐藏并且没有创建元素,有什么问题吗?应该在我标记复选框时发生这些情况,如果我取消标记另一方面,该过程应该被还原意味着div#options_holder将被隐藏并且其中的任何元素都应该被破坏,有什么问题?

4

1 回答 1

1

确保您的选择器正常工作并且您的 ID 正确通常很容易被忽略。很高兴我们可以帮助您找到您的打字错误:-)

工作代码小提琴:http: //jsfiddle.net/pXJpr/

HTML:

<div id="choices">
    <input type="checkbox" name="testName" id="testId" />
</div>
<div id="options_holder" style="display:none;">
</div>

JS:

var counter = 1;

$('#choices').on("change", ":checkbox", function(e) {
    var theName = $(this).attr('name');
    var theID = $(this).attr('id');
    var isChecked = $(this).prop("checked");
    var input, button, append = "";

    $("#options_holder").show();

    input = capitalize(theName) + '<input name="input_' + theName + '[]" id="' + theID + '" value="" placeholder="' + capitalize(theName) + '" />';
    button = '<button type="button" class="add-size">Nuevo ' + capitalize(theName) + '</button>';

    append = counter === 1 ? input += button : input;

    $("#options_holder").append(append);
    counter++;

    console.log("You changed " + theName + ", with an id of " + theID + ", its checked property is: " + isChecked);
});

function capitalize(s) {
    return s;
}
于 2013-09-11T16:53:07.790 回答