让我们考虑一下这个功能:
function validateField(selector) {
$(selector).on("change, blur", function() {
// do stuff
});
}
该元素可以有一个id = selector或一个class = selector。我该如何进行这种抽象?
答案 0 :(得分:3)
您可以通过执行以下操作来简单地引用两个:
function validateField(selector) {
var $selector = $('#'+selector+', .'+selector); // This will reference every class and id with the selector's name
$selector.on("change, blur", function() {
// do stuff
});
}
答案 1 :(得分:1)
您可能想尝试这样的事情,尝试先查看它是否为ID,如果它返回0作为长度,请尝试上课。但这不是一个很好的方法,也许你也可以尝试用旗帜
function validateField(selector) {
var $selector = $('#' + selector);
if ($selector.length === 0) {
$selector = $('.' + selector)
}
$selector.on("change, blur", function() {
// do stuff
});
}
带有标志
function validateField(selector, classSelect) {
var $selector;
if (classSelect === true) {
$selector = $('.' + selector)
} else {
$selector = $('#' + selector)
}
$selector.on("change, blur", function() {
// do stuff
});
}
答案 2 :(得分:1)
此功能将同时包含ID和类选择器:
function validateField(selector, Type) {
var SelectorString = "";
if (Type == "ID")
SelectorString = "#" + selector;
else if (Type == "Class")
SelectorString = "." + selector;
else
return; // invalid so don't create event handler.
$(SelectorString).on("change, blur", function() {
// do stuff
});
}