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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:54:41  来源:igfitidea点击:

jQuery console.log() vs alert()

javascriptjqueryjavascript-events

提问by Schutzstaffel

jQuery code:

jQuery代码:

$(document).bind('click', function(e) {
    console.log(e.target);
    alert(e.target);
});

The e.targetcontains 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.targetis 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.logis 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 outerHTMLproperty of the DOM Element object:

console.log当您想查看对象的属性时很有用,但alert()只显示对象的类型,如果您想查看元素的真实 html,可以使用outerHTMLDOM Element 对象的属性:

alert(e.target.outerHTML);

http://jsfiddle.net/phLVu/

http://jsfiddle.net/phLVu/

回答by palmplam

See this other SO question:

看到这个其他SO问题

You have to use the outerHTMLattribute.

您必须使用该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;