使用常见的“如果 ID 存在”方法发现 here ,当将 ID 与如下所示的数组变量连接时,是否仍然可以检查 ID 是否存在?
for (var i=0; i < lineData.length; i++)
{
optionData = lineData[i].split(",");
if ($("#" + optionData[0]).length)
{
$("#" + optionData[0]).text(optionData[1]);
}
}
在调试中运行此命令时,如果连接的 $("#"+ optionData[0])
ID 不存在,则会产生“undefined: undefined”结果并跳转到:
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
在 JQuery 代码中。
以这种方式使用检查和设置 HTML ID 是否符合代码规范?为什么这在流行的“存在”方法中不起作用?我可以做些什么来修复它并使其跳过使用这种类型的 ID 与数组字符串串联时不存在的 ID?
最佳答案
http://jsfiddle.net/P824r/工作正常,所以问题不在你想的地方。简化您的代码并添加一些检查。你也没有做任何需要 jQuery 的事情,所以我不明白这是一个 jQuery 问题,但是很好:
function handler(data, i) {
var optionData = data.split(","),
$element;
if (optionData[0] && optionData[1]) {
$element = $("#" + optionData[0]);
if ($element.length > 0) {
// omitting >0 as 'trick' causes JS coercion from number to boolean.
// there's literally no reason to ever do so: it's both slower and
// hides your intention to others reading your code
$element.text(optionData[1]);
}
} else { console.error("unexpected optionData:", optionData);
}
lineData.forEach(handler);
但是我们可以在没有 jQuery 的情况下做到这一点,因为我们并没有真正使用普通 JS 无法做到的任何事情,在相同数量的调用中:
function handler(data) {
var optionData = data.split(",");
if (optionData.length === 2) {
var id = optionData[0],
content = optionData[1],
element = document.getElementById(id);
// because remember: ids are unique, we either get 0
// or 1 result. always. jQuery makes no sense here.
if (element) {
element.textContent = content;
}
} else { console.error("unexpected input:", optionData);
}
lineData.forEach(handler);
(非 jquery 版本将 optionsData 解压到单独的变量中以提高易读性,但最终的易读性是确保 lineData
不包含字符串,而只包含开始时正确键入的对象与,所以我们可以做一个 forEach(function(data) { ... 直接使用 data.id 和 data.content ... })
)
关于javascript - 使用 .length 通过 concat 数组检查 JQuery 中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22844902/