inner text of element passed as <span onclick=foo(this) &

inner text of element passed as <span onclick=foo(this) >myText</span>

本文关键字:onclick foo this span lt of text element passed inner as      更新时间:2023-09-26

HTML:

<span onclick="foo(this);" >myText</span>

JavaScript函数中,我需要获取此span元素的innerText。

 function foo(parameter) {
             alert($(parameter).text);                       
         }

它总是返回undefined。我尝试过innerHTML、textContent等,但没有任何帮助。

您需要调用text作为函数,因为它实际上是jQuery函数。

function foo(parameter) {
         alert($(parameter).text());                       
     }

或通过原始JavaScript

function foo(parameter) {
         alert(parameter.textContent);                       
     }

看起来您正在使用jQuery,所以请使用.html()

function foo(parameter) {
    alert($(parameter).html());
}

使用JQUERY

看看这把小提琴

您可以使用jQuery的html()函数。你应该重写你的Javascript如下

function foo(parameter) {
    alert($(parameter).html());
}

请阅读文档中有关html()的更多信息

使用Java脚本

看看小提琴

使用纯javascript,可以按如下方式完成。为此,您应该使用innerHTML

function foo(parameter) {
    alert(parameter.innerHTML);
}

请阅读文档

中有关innerHTML的更多信息