JavaScript - 打印元素值

标签 javascript

我有以下内容:

<div onclick="updateElementWithValue()" id="element">Value 1</div>
<div onclick="updateElementWithValue()" id="element">Value 2</div>
<div onclick="updateElementWithValue()" id="element">Value 3</div>

JS:

updateElementWithValue(){
//need to add some code here to make the function work!
alert('This is element : ');
}

我想要做的是,例如,如果我点击:

<div onclick="updateElementWithValue()" id="element">Value 2</div>

它显示该div的值,在上面的情况下,它应该显示:值2

有什么想法吗?

最佳答案

第一:不要对多个元素使用相同的 id。

第二:将元素作为参数:updateElementWidthValue(this)

功能是:

function updateElementWithValue(element) { 
    alert('This is element: ' + element.innerHTML);
}

关于JavaScript - 打印元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37100318/

相关文章:

javascript - o[str] 与 (o => o.str)

javascript - 模拟链式方法

javascript - 在javascript问题中读取xml

javascript - 处理多个条件的正则表达式

javascript - 如果此位置使用 calc() 函数,我如何使用 Javascript 设置元素的位置?

javascript - react 和传单

javascript - Node.js Express 不会提供绝对 URL .js 文件

java - GWT:如何确保在构建 GWT 页面后运行 JavaScript

javascript - 在 Javascript 中为数组中的数组推送语法

javascript - Struts2 - jQuery Ajax 表单在 jQuery 对话框中发送数据 (POST) 2 次