我正在尝试编写一些用于调试辅助功能的脚本,基本上我需要在控制台上告诉我哪个元素具有焦点的内容。但我不想知道所有内容,仅是html上打印的内容。因此,console.log($(this))虽然简单,但它并不是我想要的。

这是我的代码,第一个功能是获取属性

(function($) {
  var _old = $.fn.attr;
  $.fn.attr = function() {
    var a, aLength, attributes, map;
    if (this[0] && arguments.length === 0) {
            map = {};
            attributes = this[0].attributes;
            aLength = attributes.length;
            for (a = 0; a < aLength; a++) {
                    map[attributes[a].name.toLowerCase()] = attributes[a].value;
            }
            return map;
    } else {
            return _old.apply(this, arguments);
    }
  }
}(jQuery));

$('*').each(function() {
  $(this).on('focus', function() {
    var attributes = JSON.stringify($(this).attr());
    var replaced = attributes
                    .replace(/{|}|,/g,' ')
                    .replace(/:/g, "=")
                    .replace(/"class"/, 'class')
                    .replace(/"id"/, 'id')
                    .replace(/"href"/, 'href')
                    .replace(/"title"/, 'title')
                    .replace(/"target"/, 'target');
    var tag = $(this).prop('tagName').toLowerCase();
    console.log('<'+tag+replaced+'>...</'+tag+'>');
  });
});


所以,如果我的html就像

<a class="link" id="blue" href="w.com" target="_blank" title="vfs">link</a>


我懂了

<a class="link" id="blue" href="w.com" target="_blank" title="vfs">...</a>


这正是我想要的。问题:如您所见,我删除属性周围引号的方式非常糟糕。除非我列出所有可能的属性,否则我会得到不必要的引号。有什么想法吗?也许我需要在分类之前将其删除。

https://jsfiddle.net/8xnuepk9/

最佳答案

您无需弄乱属性。 Cloning节点,然后更改克隆的内部html即可完成所需的操作。

$('*').on('focus', function() {
    var clone = $(this).clone();
    clone.html('..')
    console.log(clone[0]);
});


JSFiddle

关于javascript - jQuery聚焦元素荧光笔,对属性进行字符串化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32703514/

10-12 12:27
查看更多