jqueryを使用してチェックボックスがチェックされているときに新しいdivタグを追加する方法
質問
新しいdivタグを追加する方法チェックボックスがオンになっている場合、および2つのチェックボックスがオンになっている場合、2つのdivタグを表示する必要があります。 jqueryを使用してこのモジュールを解決するために私を助けてください
解決
$(':checkbox').click(function () {
if ($(this).attr('checked')) {
// create new div
var newDiv = $('<div>contents</div>');
// you can insert element like this:
newDiv.insertAfter($(this));
// or like that (choose syntax that you prefer):
$(this).after(newDiv);
} else {
// this will remove div next to current element if it's present
$(this).next().filter('div').remove();
}
});
チェックボックスのラベルの横にこの新しいdivを追加したくない場合は、まずチェックボックスにIDが設定されていることと、ラベルの属性に使用してチェックボックスでラベルを接続することを確認してください:
<label for="myCb1">test</label>
<input type="checkbox" id="myCb1" value="1" />
これで、JSコードを少し変更するだけで完了です。
$(':checkbox').click(function () {
// current checkbox id
var id = $(this).attr('id');
// checkbox' label
var label = $('label[for=' + id + ']');
if ($(this).attr('checked')) {
// create new div
var newDiv = $('<div>contents</div>');
// insert div element
newDiv.insertAfter(label);
} else {
// this will remove div next to current element if it's present
label.next().filter('div').remove();
}
});
所属していません StackOverflow