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

标签 javascript jquery html

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

标记

<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/

相关文章:

javascript - 如何判断是什么触发了 jQuery focus()?

javascript - 从 redux 中的数组中删除项目

java - ServletFileUpload - ItemIterator 的顺序

javascript - 为什么 `value` 属性为空而 `value` 属性具有正确的值?

javascript - jquery sibling 如何删除类?

php - 如何用 PHP 和 JSON 填充表格?

javascript - 使用 jQuery .load 函数刷新元素而不重复它

jquery - 在 SmartWizard 中后退时跳过验证

jquery - 如何解决响应中的高度问题?

html - CSS 背景图像仅适用于内联 html