如何能够例如这个HTML元素/标签:套装属性上点击
<input type="checkbox" id="1234" checked onClick="replace(1234)"> I have a car<br>
替换为点击
<input type="checkbox" id="1234" unchecked onClick="replace(1234)"> I have a car<br>
时,我想只更换输入标签和更改HTML代码在临时位置
谢谢
如何能够例如这个HTML元素/标签:套装属性上点击
<input type="checkbox" id="1234" checked onClick="replace(1234)"> I have a car<br>
替换为点击
<input type="checkbox" id="1234" unchecked onClick="replace(1234)"> I have a car<br>
时,我想只更换输入标签和更改HTML代码在临时位置
谢谢
这将检查元素是否具有属性checked
,如果是的话那么它就会删除它,并设置一个新的属性,下面的代码称为unchecked
function replace(id) {
var attr = $("#" + id).attr('checked');
// For some browsers, `attr` is undefined; for others,
// `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
$("#" + id).removeAttr('checked').attr("unchecked", "")
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="1234" checked onClick="replace(1234)"> I have a car<br>
使用。它会帮助你:
$('#1234').click(function(){
if($(this).is(':checked'))
$(this).attr('checked',true);
else
$(this).removeAttr('checked');
});
的'checked'属性,那是类型错误,谢谢你注意到一个 – vishu
$('#1234').click(function(){
if($(this).is(':checked')) {
$(this).attr('checked',true);
console.log('checked')
}
else {
$(this).attr('checked',false);
console.log('unchecked')
}
});
<!DOCTYPE html>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</header>
<body>
<input type="checkbox" id="1234" checked > I have a car<br>
</body>
</html>
请检查上面的代码片段。它可能有帮助。
可以直接调用复选框,单击事件如下图所示代码
$(document).on("click", "input[name='chk']", function() {
//alert(this.id);
debugger;
var ischecked2 = $(this).is(':checked');
if (ischecked2) { //checked
console.log("checked");
} else { //unchecked
console.log("unchecked");
}
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.0.min.js">
</script>
<input type="checkbox" id="1234" name="chk"> I have a car<br>
那你试试这么远吗? – kosmos
'unchecked'不是有效的HTML属性。你也不需要替换整个元素,你只需要读取元素 –