[英]Why doesn't $(this) work here?
在這個JSfiddle 中有兩個 forms。
這是重復兩次
<form action="" method="post">
<input id="element" signed type="checkbox" checked>
<label for="element">x</label>
<button type="submit">Submit</button>
</form>
JQuery 看起來像這樣
$('form').live('submit', function(){
if ($("input[type=checkbox]").is(':checked')){
$("label").show();
}else{
$("label").hide();
}
return false;
});
我不能使用 ID 來區分 forms,所以我想我只剩下這個$(this)
。
如果最后一個表單被刪除,它應該可以正常工作,但問題是在不使用 ID 的情況下讓它與許多表單一起工作。
但是,如果我將代碼更改為
$('form').live('submit', function(){
if ($(this).("input[type=checkbox]").is(':checked')){
$(this).("label").show();
}else{
$(this).("label").hide();
}
return false;
});
它不起作用。
我究竟做錯了什么?
$(this).("input[type=checkbox]")
不是有效的代碼——你正在使用括號來調用某些東西,但在它們前面沒有任何東西可以調用。 您需要從 jQuery 化表單中調用.find()
或 .children( .children()
:
$(this).find("input[type=checkbox]")
這是給你的精簡版:
$( 'form' ).live( 'submit', function()
{
var $this = $( this );
$this.find( 'label' ).toggle( $this.find( 'input[type="checkbox"]' ).is( ':checked' ) );
return false;
} );
您需要一個方法名稱。
method, which searches all descendants:您可以使用find()
方法來搜索所有后代:
$(this).find("label").show();
method, which only searches direct descendants. ...或children()
方法,它只搜索直系后代。
$(this).children("label").show();
您的代碼可能如下所示:
$('form').live('submit', function(){
if ($(this).find("input[type=checkbox]").is(':checked')){
$(this).find("label").show();
}else{
$(this).find("label").hide();
}
return false;
});
$("input[type=checkbox]", this).is(':checked')
嘗試這個:
$('form').live('submit', function(){
// Cache "this" reference
var $this= $(this);
if ($this.find("input[type=checkbox]").is(':checked')){
$this.find("label").show();
}else{
$this.find("label").hide();
}
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.