使用 javascript 获取元素内的文本
Get text inside an element using javascript
我正在尝试使用 jquery 在 div 中获取文本内容。但它 returns 'undefined'。请有人告诉我我在这里做错了什么。这是我的代码。
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).textContent;
console.log(text);
});
您正在重新选择带有 jQuery 的元素,您不需要这样做。试试这个
$(document).on('click','.exc_text',function(){
var text = this.textContent;
console.log(text);
});
解决这个问题的最简单方法是查看开发工具。我所做的只是在第二个 link 处中断,然后将鼠标悬停在它上面,这表明它是一个元素,因此无需重新选择它...
您应该使用 .text()
而不是 .textContent
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).text();
console.log(text);
});
textContent
是原生元素上的 属性,而不是 jQuery 对象上的。 $(this)
将 this
(本机 DOM 元素)包装在 jQuery 对象中。
要么坚持原生 DOM api(并使用 textContent
)——这是我的建议:
document.addEventListener('click', (e) => {
if (e.target.classList.contains('exc_text') {
console.log(e.target.textContent);
}
})
如果必须,请坚持使用 jQuery(并使用 .text()
):
$(document).on('click', '.exc_text', function(){
var text = $(this).text();
console.log(text);
});
只需简单地使用 .text()
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text', function(){
var text = $(this).text();
console.log(text);
});
我正在尝试使用 jquery 在 div 中获取文本内容。但它 returns 'undefined'。请有人告诉我我在这里做错了什么。这是我的代码。
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).textContent;
console.log(text);
});
您正在重新选择带有 jQuery 的元素,您不需要这样做。试试这个
$(document).on('click','.exc_text',function(){
var text = this.textContent;
console.log(text);
});
解决这个问题的最简单方法是查看开发工具。我所做的只是在第二个 link 处中断,然后将鼠标悬停在它上面,这表明它是一个元素,因此无需重新选择它...
您应该使用 .text()
而不是 .textContent
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).text();
console.log(text);
});
textContent
是原生元素上的 属性,而不是 jQuery 对象上的。 $(this)
将 this
(本机 DOM 元素)包装在 jQuery 对象中。
要么坚持原生 DOM api(并使用 textContent
)——这是我的建议:
document.addEventListener('click', (e) => {
if (e.target.classList.contains('exc_text') {
console.log(e.target.textContent);
}
})
如果必须,请坚持使用 jQuery(并使用 .text()
):
$(document).on('click', '.exc_text', function(){
var text = $(this).text();
console.log(text);
});
只需简单地使用 .text()
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text', function(){
var text = $(this).text();
console.log(text);
});