引用https://stackoverflow.com/a/46159513/1620626的解决方案在@osdavison 的大力帮助下。
现在我希望脚本在没有预定义的情况下找到它的子class
或id
。我现在只想创建一个函数
。所以我希望这样做。
JS
function cloneAllz(chkBoxID, clsName) {
alert(chkBoxID + '/' + clsName);//test value
var $input1 = $(document).find('#' + clsName).filter(':visible:first'); //find the first input begins with *box or other same id???
$input1.keypress(function() { //duplicate the first box typing
var $this = $(this);
window.setTimeout(function() { //delay a bit
if ($('#' + chkBoxID).is(':checked')) { //if checkbox empty
$('*[id^="' + clsName + '"]').val($this.val()).attr('readonly', true); //clone all inputs and set them readonly
$input1.attr('readonly', false);
}
}, 0);
});
}
HTML
1.
<input type="text" value="" id="box1" />
<label>
<input type="checkbox" id="cloneAll" onChange="cloneAllz('cloneAll','box')" />clone all</label>
<br /> 2.
<input type="text" value="" id="box2" />
<br /> 3.
<input type="text" value="" id="box3" />
<br /> 4.
<input type="text" value="" id="box4" />
<br /> 5.
<input type="text" value="" id="box5" />
<br /> .
<br /> .
<br /> .
<br /> 100.
<input type="text" value="" id="box100" />
<br />
我从控制台得到的只是Uncaught ReferenceError:cloneAllz未定义
最佳答案
首先,你的 fiddle 使用的是 jQuery 1.5.2,它非常已经过时了。您应该尽快更新。
其次,您应该使用不显眼的事件处理程序,而不是 HTML 中的事件属性。
要解决您的实际问题,您可以 Hook 第一个 input
的 input
事件。在该事件处理程序中,您可以检查该复选框是否已选中,如果选中,则将所有其他输入的 val()
设置为与当前输入相匹配。使用此方法将大大简化目前看起来有点过于复杂的代码。试试这个:
$('.container .master').on('input', function() {
var $container = $(this).closest('.container');
if ($container.find('.cloneAll').is(':checked'))
$container.find('input:not(.master)').val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
1. <input type="text" value="" class="master" />
<label>
<input type="checkbox" class="cloneAll" />
clone all
</label><br />
2. <input type="text" value="" id="box2" /><br />
3. <input type="text" value="" id="box3" /><br />
4. <input type="text" value="" id="box4" /><br />
5. <input type="text" value="" id="box5" /><br />
.<br /> .<br /> .<br />
100. <input type="text" value="" id="box100" />
</div><br /><br />
<div class="container">
1. <input type="text" value="" class="master" />
<label>
<input type="checkbox" class="cloneAll" />
clone all
</label><br />
2. <input type="text" value="" id="box2" /><br />
3. <input type="text" value="" id="box3" /><br />
4. <input type="text" value="" id="box4" /><br />
5. <input type="text" value="" id="box5" /><br />
.<br /> .<br /> .<br />
100. <input type="text" value="" id="box100" />
</div>
关于javascript - 如何在选中复选框(动态)的情况下克隆第一个框中的每个输入的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46159961/