我对checkbox(id="yes")
产生影响,它会启用texbox(其id为“string”)点击。我能够克隆div。但是之后这个效果不起作用。谁能帮我吗?
HTML:
<form id="form" name="myForm">
<div id="duplicater">
<div id="duplicate">
<label>Machine</label>
<select>Select<option>Opt1</option></select>
<label>Connection Type</label>
<select><option>Select Connection Type</option>
</select>
<label>Command To Test</label><input type="text" value="command" />
<label>Validate</label><input type="checkbox" name="yes" value="yes" id="yes"
onclick="enableDisable()">
<label>Validate String</label><input type="text" id="string" name="string" size="10"
disabled></div></div>
<input type="button" value="+" class="add">
</form>
JS CODE:
<script type="text/javascript">
$(document).ready(function(){
$(".add").click(function () {
var c=$('#duplicate').clone(true,true);
$('#duplicater').append(c);
$('#yes').append(function() {
return $('#yes').click(enabledisable);
})
});
});
function enableDisable() {
if(document.myForm.yes.checked){
document.myForm.string.disabled = false;
} else {
document.myForm.string.disabled = true;
}
}
window.onload = enableDisable;
</script>
答案 0 :(得分:0)
根据w3c建议,您不能使用相同的ID两次。如果你使用它,javascript / jquery将始终引用文档中的第一个元素。
因此更新代码并使用类而不是ID
<label>Validate</label><input type="checkbox" name="yes" value="yes" class="validate-yes">
<label>Validate String</label><input type="text" class="validate-string" name="validate-string" size="10" disabled>
并使用此js代码:
$(document).ready(function(){
$(".add").click(function () {
var c=$('.duplicate').clone(true,true);
$('#duplicater').append(c);
});
$('#form').on('click', '.validate-yes', function(){
if($(this).is(':checked')){
$(this).parent().find('.validate-string').prop('disabled', false);
} else {
$(this).parent().find('.validate-string').prop('disabled', true);
}
});
});
答案 1 :(得分:0)
.clone( [withDataAndEvents ] [, deepWithDataAndEvents ] )
withDataAndEvents (default: false)
Type: Boolean
A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back to false in 1.5.1 and up.
deepWithDataAndEvents (default: value of withDataAndEvents)
Type: Boolean
A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).
另请参阅Event Deligation并使用jQuery ON绑定事件