为什么对象的控制台日志输出一个字符串?

时间:2016-03-24 16:56:45

标签: javascript contenteditable

以下代码选择光标所在的当前节点:

var selection;
    if (window.getSelection){
        selection = window.getSelection();
    }
else if (document.selection && document.selection.type !== "Control") {
    selection = document.selection;
}
var anchor_node = selection.anchorNode; //current node on which cursor is positioned
console.log(anchor_node);

console.log说" text"那是节点的内容;但是anchor_node实际上是一个对象

$('.result').val(anchor_node);

输出" [对象对象]&#34 ;;它使用:

$('.result').val(anchor_node.data);

那么为什么日志只输出内容字符串?如何记录整个anchor_node对象?

1 个答案:

答案 0 :(得分:3)

您还没有提到您正在使用的浏览器/调试器,但Chrome的开发工具将通过呈现其外部HTML来输出该元素,但它是实时可点击的;您甚至可以右键单击它,如果需要,选择“在元素面板中显示”。

另一个选择(因为nikhil删除了他的答案,不知道为什么,去投票并且它不再存在)是使用console.dir,它不会试图专门处理DOM元素。 / p>

重新console.log对DOM元素的特殊处理(在某些开发工具中):

例如:

console.log(document.querySelector("a"));
<a href="http://example.com">This is the anchor</a>

日志示例,我将光标悬停在它上面 - 注意它如何突出显示页面上的元素:

enter image description here

右键单击,我可以选择元素面板中的显示:

enter image description here

如果我这样做的结果:

enter image description here