gpt4 book ai didi

javascript - 如何将 args 传递给事件处理程序?

转载 作者:数据小太阳 更新时间:2023-10-29 04:28:12 24 4
gpt4 key购买 nike

如何将参数传递给事件处理函数?这在页面加载时运行函数,这不是预期的效果。我需要这个例程 validateText 来针对几个不同的文本框、下拉组合运行。我可以重用 validateText 而不是为每个文本/下拉组合创建一个吗?

//add blur event handler to the textbox with jQuery when the page is finished loading
$(document).ready(function() {
$("#myTextbox").blur(validateText($("#myTextbox"), $("#Select1")));
})


function validateText(textbox, dropdown) {

var message = $("#message");
var isValid = false;
//get the value the user type in
var textboxValue = $(textbox).val();

//get the options from the lookup
var options = $("option", dropdown);

//loop through the options and compare it to "value"
options.each(function() {
var optValue = $(this).val();
if (optValue === textboxValue) {
isValid = true;
}
});

if (!isValid)
message.text(textboxValue + " is not a valid value from the list.");
else
message.text(textboxValue + " is perfectly valid.");
}

最佳答案

使用绑定(bind)将额外参数传递给事件监听器:

http://docs.jquery.com/Events/bind

$(document).ready(function() {
$("#myTextbox").bind("blur", [ $("#myTextBox"), $("#Select1")], validateText);
})

然后从event.data访问数据:

function validateText(event) {
textBox = event.data[0];
dropdown = event.data[1];
}

关于javascript - 如何将 args 传递给事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1230230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com