gpt4 book ai didi

javascript - 在 jQuery 可枚举函数中操作 HTML5 数据值引发错误的案例

转载 作者:行者123 更新时间:2023-11-30 17:29:22 25 4
gpt4 key购买 nike

标题看起来有点乱,我举个例子:

标记

<div id="MyDiv"></div>
<div id="SecondaryDiv"></div>

JS

// Set the HTML5 data key 'name' to value 'MyName'
$("#MyDiv").data("name", "MyName");

// Return all divs with the data key 'name' matching 'MyName'
// This works without a hitch
$("div").filter(function () {
return $(this).data("name") === "MyName";
});

// This breaks because I try to add '.toLowerCase()' to the end of the .data() function.
// The error returned is:
// TypeError: $(...).data(...) is undefined
$("div").filter(function () {
return $(this).data("name").toLowerCase() === "myname";
});

在比较 $(...).data(...) 值时如何忽略大小写?

作为旁注,即使我这样做:

// This throw an error saying:
// TypeError: val is undefined
var val = "";
$("div").filter(function() {
val = $(this).data("name");
return val.toLowerCase() === "myname";
});

最佳答案

你不能在 undefined 上运行 .toLowerCase(),所以测试 .data('name') 的返回值首先是未定义的:

$("div").filter(function () {
if ($(this).data("name")) {
return $(this).data("name").toLowerCase() === "myname";
} else {
return false;
};
});

http://jsfiddle.net/mblase75/yX4X2/

或更简洁:

$("div").filter(function () {
return $(this).data("name") && ($(this).data("name").toLowerCase()==="myname");
});

http://jsfiddle.net/mblase75/yX4X2/1/


(但是,请注意 $(this).data("name") 可能会返回“假”值,例如 false0,因为 .data() 尝试将字符串转换为适当的类型。参见 this question。)

关于javascript - 在 jQuery 可枚举函数中操作 HTML5 数据值引发错误的案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23481605/

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