javascript 使用 jQuery 获取点击的元素 html?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12443229/
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
Get clicked element html with jQuery?
提问by lisovaccaro
I'm listening for clicks of a number of element's. I want to show an alert when an user clicks on one, the alert's content should be the clicked element's innerHtml.
我在听一些元素的点击。我想在用户点击一个警报时显示一个警报,警报的内容应该是被点击元素的innerHtml。
$(".tags-container > p").click(function (event) {
alert('inner html');
});
I could do it by adding the code to the html, but I prefer to use a jquery listener.
我可以通过将代码添加到 html 来实现,但我更喜欢使用 jquery 侦听器。
How can I show the element's innerHTML on the alert?
如何在警报中显示元素的 innerHTML?
采纳答案by Nope
How do I get the clicked inner html on click?
如何在点击时获得点击的内部 html?
If you are asking how to get the HTML out of the <p>
tag then the following should do it.
如果您要问如何从<p>
标签中取出 HTML,则应执行以下操作。
Using jQuery only to attach event and get value using jQuery's html():
仅使用 jQuery 来附加事件并使用 jQuery 的html()获取值:
$(".tags-container > p").click(function(event) {
alert($(this).html());
});?
Using a mixture, attach event using jQuery and get value using JavaScript's innerHTML:
使用混合,使用 jQuery 附加事件并使用 JavaScript 的innerHTML获取值:
$(".tags-container > p").click(function(event) {
alert(this.innerHTML);
});?
DEMO
演示
NOTE
笔记
However, if all you want is the text within than use the text()method instead, which will strip out any HTML tags you may have inside and just return the combined text.
但是,如果您想要的只是其中的文本,那么请改用text()方法,这将去除您可能拥有的任何 HTML 标签并仅返回组合文本。
$(".tags-container > p").click(function(event) {
alert($(this).text());
});?
回答by Telework Inc.
Like they said, just use $.html(). Personally, I'd just use innerHTML because $.html() filters out br elems and such; I'd just turn them into newlines.
就像他们说的,只需使用 $.html()。就个人而言,我只使用 innerHTML 因为 $.html() 过滤掉 br elems 等;我只是把它们变成换行符。
$(".tags-container > p").click(function () {
alert(this.innerHTML.replace(/<br>/, '\n'));
});
回答by Gung Foo
$(".tags-container > p").click(function () {
alert($(this).html());
});
回答by Mohammed Swillam
use jQuery's html()
function
使用 jQuery 的html()
函数
$(".tags-container > p").click(function (event) {
alert($(this).html());
});
a working example: http://jsfiddle.net/ukxvp/
一个工作示例:http: //jsfiddle.net/ukxvp/