我的网站上有几个模块,每个模块都可以由用户禁用。 我的问题是每个模块都有一个完整的脚本,因此我的问题是:如何将其放入一个脚本中(->也许一个 jQuery-click-function?)
(我忽略了模块是否启用或禁用的数据库部分,因为它不相关)
HTML
<div class="border f12" style="width: 200px">
<b>Weather Module</b>
<p style="text-align: justify; margin: 0px;">Description</p><br>';
<button action="del" startmodule="weather" id="submit_weather"><span class="ui-button-icon-primary ui-icon ui-icon-trash"></span><span class="ui-button-text">disable/enable</span></button>
</div>
<div class="border f12" style="width: 200px">
<b>Infos Module</b>
<p style="text-align: justify; margin: 0px;">Description</p><br>';
<button action="del" startmodule="infos" id="submit_infos"><span class="ui-button-icon-primary ui-icon ui-icon-trash"></span><span class="ui-button-text">disable/enable</span></button>
</div>
JAVASCRIPT
<script>
$("#submit_infos").click(function() {
$(".ajax_response").empty();
$.post("settings/settings_startmodule.php",
{
ajax_action: $("#submit_infos").attr("action"),
ajax_startmodule: $("#submit_infos").attr("startmodule")
},
function(data) {
$(".ajax_response").html(data);
}
);
});
$("#submit_weather").click(function() {
$(".ajax_response").empty();
$.post("settings/settings_startmodule.php",
{
ajax_action: $("#submit_weather").attr("action"),
ajax_startmodule: $("#submit_weather").attr("startmodule")
},
function(data) {
$(".ajax_response").html(data);
}
);
});
</script>
最佳答案
您的方法是相同的,并且可以轻松转换为对所有模块使用单个click
处理程序。您需要某种方法来选择模块中使用的所有按钮 - 从您的 HTML 中我可以发现多种方法
div.f12 按钮
作为选择器 - 相当不错button[startmodule]
作为选择器 - 相当好,但速度较慢button[id^='submit_']
作为选择器 - 相当糟糕!速度慢并且可能容易出错
但是,最好的方法是在每个按钮上都有一个公共(public)类并将其用作选择器。
<button class="module-button" action="del" startmodule="infos">...</button>
给定选择所有按钮的通用方法,只需使用此脚本(假设您在所有按钮上都有一个通用类module-button
):
$(".module-button").click(function() {
$(".ajax_response").empty();
var $this = $(this); // variable refers to the button having been clicked
$.post("settings/settings_startmodule.php",
{
ajax_action: $this.attr("action"),
ajax_startmodule: $this.attr("startmodule")
},
function(data) {
$(".ajax_response").html(data);
}
);
});
关于javascript - 将多个 jQuery 单击功能合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560969/