2017-04-19 53 views
-2

如何能夠例如這個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代碼在臨時位置

謝謝

+1

那你試試這麼遠嗎? – kosmos

+1

'unchecked'不是有效的HTML屬性。你也不需要替換整個元素,你只需要讀取元素 –

回答

0

這將檢查元素是否具有屬性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>

0

使用。它會幫助你:

$('#1234').click(function(){ 
    if($(this).is(':checked')) 
     $(this).attr('checked',true); 
    else 
     $(this).removeAttr('checked'); 
}); 
+1

的'checked'屬性,那是類型錯誤,謝謝你注意到一個 – vishu

1

$('#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>

請檢查上面的代碼片段。它可能有幫助。

0

可以直接調用複選框,單擊事件如下圖所示代碼

$(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>