[英]click on a parent div to trigger checkbox submission?
我有一組復選框可以關閉和打開一組用戶的權限,我希望能夠單擊每個復選框的父div來觸發ajax腳本,而不必單擊復選框本身。 除了聲明('.permission-box'),我可以以某種方式聲明權限框的父級嗎?
謝謝
<script>
//<![CDATA[
$(function() {
$('.permission-box').click(function() {
//this is what goes into $_POST
var data = 'single_permission=' + $(this).attr('value') + '&status=' + $(this).is(':checked');
$.ajax({
//This would be the url that would handle updating the MySQL Record
url: "pages/Permissions_action.php",
cache: false,
type: 'POST',
data: data,
success: function(response) {}
});
});
}); //]]>
</script>
有很多寫方法,無論如何,這里就是其中一種。
首先將click事件綁定到權限框的父級。 然后,在事件處理程序中不要忘記再次獲取子復選框,並選中/取消選中該子復選框。
<script>
//<![CDATA[
$(function(){
$('.permission-box').parent().on('click', function() {
// Obtain checkbox:
var checkbox = $(this).find(".permission-box");
// Switch checked state
checkbox.attr('checked', !checkbox.is(':checked'));
// this is what goes into $_POST
var data = 'single_permission='+ checkbox.attr('value') +'&status=' + checkbox.is(':checked');
$.ajax({
//This would be the url that would handle updating the MySQL Record
url: "pages/Permissions_action.php",
cache: false,
type: 'POST',
data: data,
success: function(response) {
}
});
});
});//]]>
</script>
您可以使用$('。permission-box')。parent()。click()
您還應該查看jQuery On()的頁面。 如果我是正確的,那是在jQuery中創建事件列表的正確方法。
或者,您可以將label-tag用作div,然后以這種方式設置樣式。
<label for="checkbox1">
<span>Some text and/or images</span>
<input type="checkbox" value="myValue" id="checkbox1" />
</label>
如果沒有javascript,就可以解決問題。
在這里,我們將使用.permission-box
類.permission-box
所有元素的父級,然后綁定一個命名空間的click事件。
事件命名空間是一種技術,它使我們可以根據所使用的事件名稱空間來不同地處理任務,當您將多個偵聽器附加到同一事件,並且只需要對其中一個進行某些操作時,此方法非常有用。
看一下這些鏈接:
使用jQuery 1.7+
$(function() { //document.ready
//We get all parent elements to delegate the click handler
$('.permission-box').parent().addClass("parent-permission-box");
//Only one event handler is assigned to all matched elements.
//Create namespaced events is a good practice.
$(document).on("click.parentBox", ".parent-permission-box", function() {
//triggers the click on the checkbox
var chk = $(this).find('.permission-box'),
status = !chk.is(':checked'),
data;
//toggle the checked state
chk.attr('checked', status);
//build the data to send
data = { 'single_permission': chk.val(), 'status': status };
$.ajax({
url: "pages/Permissions_action.php",
type: 'POST',
data: data, //buildUrlParams(data)
success: function (response) {
//... or use the deferred .done()
}
}); //end .ajax
}); //end .click
});
//Creates the parameters object in a querystring
function buildUrlParams (obj) {
var prop, parameters = [];
for (prop in obj) {
parameters.push(prop + "=" + obj[prop])
}
parameters = parameters.join("&");
return parameters;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.