javascript - 扩展 jQuery 的问题(添加调试功能)

标签 javascript jquery attributes

我有以下 jQuery 扩展方法代码,它使用 attrString() 提供元素的所有属性作为可读字符串:

例如

$('div').attrString() returns "data-hello=Hello!, class=MyClass,"

当前代码如下所示:

// Return a debug string of all the attributes of an element (first if multiple elements)
jQuery.fn.attrString = function () {
    var result = "";
    if (this[0]) {
        $.each(this[0].attributes, function (i, attrib) {
            var name = attrib.name;
            var value = attrib.value;
            result += name + "=" + value + ", ";
        });
    }
    return result;
};

测试是:

// Valid selection - multiple matches, multiple attributes
$('#output').append("<br/>$('div').attrString() = " + $('div').attrString());

// Valid selection - single attributes
$('#output').append("<br/>$('#output').attrString() = " + $('#output').attrString());

// Empty selection
$('#output').append("<br/>$().attrString() = " + $().attrString());

JSFiddle:http://jsfiddle.net/8T38S/2/

问题:

  • if (this[0]) 是测试 jQuery 选择的正确方法吗?
  • 是否有更有效的方法将属性名称和值连接在一起
  • 最简单的方法是什么不留下尾随逗号像这样 目前有吗?
  • 是否有更好的方法可以做到这一点(例如 DOM 中某处的属性)?

最佳答案

你做得对。 if (this[0]) 是测试 jquery 选择是否不为空的多种方法之一,因为如果它为空,this[0] 将是未定义的,在 bool 上下文中计算结果为 false。为了连接属性名称和值,jquery 提供了一个 map 函数。像这样使用它:

// Returns an array: ["attr=value", "attr2=value2", etc.]
$.map(this[0].attributes, function (attrib, i) {
    var name = attrib.name;
    var value = attrib.value;
    return (name + "=" + value);
});

然后您可以使用 join 方法将它们连接成一个字符串。这将消除末尾的逗号。至于你的最后一个问题,是和否。如果您将其用于调试目的,那么您应该使用 console.logconsole.dir。这将打印某个对象的所有属性。但是,如果您想实际显示它,那么您应该使用上面提供的 map 功能。

http://jsfiddle.net/prankol57/k9kLD/

整个函数在这里:

// Return a debug string of all the attributes of an element (first if multiple elements)
jQuery.fn.attrString = function () {
    var result = "";
    if (this[0]) {
        result = $.map(this[0].attributes, function (attrib, i) {
            var name = attrib.name;
            var value = attrib.value;
            return (name + "=" + value);
        }).join(", ");
    }
    return result;
};

其余代码保持不变。

关于javascript - 扩展 jQuery 的问题(添加调试功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24062325/

相关文章:

javascript - “对象作为 React 子对象无效”

python - 属性错误 : 'FreqDist' object has no attribute 'inc'

javascript - 使用javascript获取html元素的所有属性

jquery - 带toggle()的复选框打破选中/未选中状态

python - 如何迭代创建通用树的类属性?

javascript - 使用 jQuery 获取 DOM 元素

javascript - 我知道这是一个引用周期。但这是内存泄漏吗?

javascript - 使用ajax获取不需要的字符串

javascript - 从序列化字符串中获取值

jquery - 如何在jQuery中触发自定义事件,传递原始事件和数据