2011-02-23 34 views
0

我想檢查,並取消(切換)收音機時「TD」是點擊,但保留默認輸入事件jQuery的事件「檢查」事件

<table> 
    <tr> 
     <td> 
      <input type='radio'> 
     </td> 
    </tr> 
</table> 

我的代碼嘗試:

嘗試1: http://jsfiddle.net/UJXRu/

嘗試2: http://jsfiddle.net/UJXRu/1/

嘗試3: http://jsfiddle.net/UJXRu/2/

前瞻:

$("td").click(function(e) { 
    if (!$(e.target).is("input")) { 
     var bool = !$(this).children("input").is(':checked'); 
     $(this).children("input").attr("checked", bool) 
    } 
    else{ 
     var bool2 = !$(e.target).is(':checked'); 
     $(e.target).attr('checked',bool2); 
    } 
}); 
+0

不太明白你想達到什麼。你想在單擊td或單選按鈕時檢查單選按鈕嗎?你能解釋一下你想要發生什麼,當你點擊td,當你點擊單選按鈕時?謝謝。 – Luke 2011-02-23 20:18:08

+0

我想單擊td或單選按鈕時想檢查單選按鈕 – Luccas 2011-02-23 20:19:38

+0

您是否希望單選按鈕的行爲類似於複選框? – 2011-02-23 20:32:32

回答

3

嘗試了這一點..上jsfiddle

$("td").click(function(e) { 
    if (e.target.type !== 'radio') { 
     $(this).find(":radio").trigger('click'); 
    } 
}); 

例。

如果你想使TD和單選按鈕切換收音機checked屬性,你可以做這樣的事情:

$("td").toggle(function() { 
    $(this).children(":radio").attr("checked", true); 
}, function() { 
    $(this).children(":radio").attr("checked", false); 
}); 

例如在jsfiddle

+0

謝謝,工作! – Luccas 2011-02-23 20:38:12

0

爲什麼不直接叫輸入標籤的默認點擊事件:

$(this).children("input").click(); 
+0

它不起作用 – Luccas 2011-02-23 20:15:16

0

響應您的評論:

「我想單擊td或單選按鈕「

」時檢查單選按鈕

應該是簡單的:

$("td").click(function(e) { 
    $(this).find("input").attr("checked", true); 
}); 

http://jsfiddle.net/lukemartin/UJXRu/3/

0

這個答案不把單選按鈕的檢查(用戶真的不喜歡),並試圖提供一個更現實的場景。

$("tr.myRow").click(function(e) { 
    // dont override the radio inputs default 
    if ($(e.target).hasClass("childRadio") || e.target.tagName == 'LABEL') 
     return; 

    // find the child radio, and if it's not checked, check it. 
    var $childRadio = $("input.childRadio", $(this)); 
    if (!$childRadio.attr('checked')) { 
     $childRadio.attr('checked', 'checked'); 
    } 
}); 

我去了添加標籤的麻煩,並已使用的名稱屬性,以便單選按鈕組合(這是有一個單選按鈕的原因)。因此,儘可能保持默認行爲,並且只是增加點擊來選擇特定的子單選按鈕。

html示例如下。

<tr class="myRow"> 
    <td> 
     <div>Some Content</div> 
     <div> 
      <label for="radio1">Radio 1 Label</label> 
      <input type='radio' id="radio1" class="childRadio" checked="checked" name="Group1"> 
     </div> 
     <div>More Content</div> 
    </td> 
</tr> 
<tr class="myRow"> 
    <td> 
     <div> 
      <label for="radio2">Radio 2 Label</label> 
      <input type='radio' id="radio2" class="childRadio" name="Group1"> 
     </div> 
    </td> 
</tr>