Javascript jQuery console.log() 与 alert()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12635582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery console.log() vs alert()
提问by Schutzstaffel
jQuery code:
jQuery代码:
$(document).bind('click', function(e) {
console.log(e.target);
alert(e.target);
});
The e.target
contains the name of the object which is being clicked.
For demonstration purposes, if I click on an input element, the above code prints the following :
For console.log()
:
在e.target
包含被点击的对象的名称。出于演示目的,如果我单击一个输入元素,上面的代码会打印以下内容:
对于console.log()
:
<input class="buton" type="submit" value="Send" name="Send">
For alert()
:
对于alert()
:
[object HTMLInputElement]
However, if I replace console.log(e.target)
with console.log(e.target.toString())
, it prints the same thing as alert()
, meaning:
但是,如果我替换console.log(e.target)
为console.log(e.target.toString())
,它会打印与 相同的内容alert()
,意思是:
[object HTMLInputElement]
My scope is to store the HTML code returned by console.log()
into a variable, but I can't understand the behaviour.
我的范围是将返回的 HTML 代码存储console.log()
到一个变量中,但我无法理解这种行为。
采纳答案by steveukx
In the event handler, e.target
is the element that the click originated from. Most browser consoles display this as the html string that represents the element.
在事件处理程序中,e.target
是点击源自的元素。大多数浏览器控制台将其显示为表示元素的 html 字符串。
When you use alert
, the argument supplied is converted to a string, so you'll see [object HTMLInputElement]
.
当您使用 时alert
,提供的参数将转换为字符串,因此您将看到[object HTMLInputElement]
.
To get to the HTML of an element, use:
要访问元素的 HTML,请使用:
alert(e.target.outerHTML);
回答by undefined
console.log
is useful when you want to see properties of an object, but alert()
only shows the type of an object, if you want to see the real html of an element, you can use outerHTML
property of the DOM Element object:
console.log
当您想查看对象的属性时很有用,但alert()
只显示对象的类型,如果您想查看元素的真实 html,可以使用outerHTML
DOM Element 对象的属性:
alert(e.target.outerHTML);
回答by palmplam
See this other SO question:
看到这个其他SO问题:
You have to use the outerHTML
attribute.
您必须使用该outerHTML
属性。
$(document).bind('click', function(e) {
alert(e.target.outerHTML);
});
see the jsFiddle here : http://jsfiddle.net/xhHPb/
在这里看到 jsFiddle:http: //jsfiddle.net/xhHPb/
回答by Denys Séguret
The console tool displays an object in the way the designer thought was useful, it doesn't just call the toString()
method of the object, contrary to alert
.
控制台工具以设计者认为有用的方式显示对象,它不只是调用toString()
对象的方法,与alert
.
If you want to get the HTML code of your target, simply do
如果您想获取目标的 HTML 代码,只需执行
var html = e.target.outerHTML;