我有一个按钮,单击该按钮将清除所有文本框并下拉值,现在我需要创建一个通用函数 并将我下面的 jquery 代码放在那个公共(public)函数中,这样我就可以在 button2、button3 的 jquery click 事件中调用该函数
<input type="button" value="Clear" title="clear" id="btnclear" />
<input type="button" value="" title="clear" id="btn2" />
<input type="button" value="" title="clear" id="btn3" />
// I need to place the below code in a function to use the function in remaining click events
$('#btnclear').off('click').on('click', function (RD) {
$('#txtname').val("");
});
$("#btn2").click(function () {
// I need to call the created common jquery function to clear the fields
});
$("#btn3").click(function () {
// I need to call the created common jquery function to clear the fields
});
最佳答案
只需以正常方式定义一个函数即可。然后你可以从所有的处理程序中调用它:
function clear_text() {
$("#txtname").val("");
}
$('#btnclear').off('click').on('click', function() {
clear_text();
});
$("#btn2").click(function() {
$("#tr2").show();
clear_text();
});
$("#btn3").click(function() {
$("#tr2").hide();
clear_text();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Clear" title="clear" id="btnclear" />
<input type="button" value="" title="clear" id="btn2" />
<input type="button" value="" title="clear" id="btn3" /> Text: <input type="text" id="txtname">
关于javascript - 如何创建一个通用的 jquery 函数并在点击事件中使用该 jquery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54285607/