繁体   English   中英

使用javascript中的DOM动态获取元素中的值

[英]get value in an element dynamically using DOM in javascript

亲爱的所有人,我的问题是这个。 我喜欢警报框来显示元素中所有的文本。 我可以知道怎么做吗?

我的想法:

<a onclick="displaytext(something)">testing</a>

function displaytext(something){
  alert(something);
}

有人可以帮我解决这个问题吗? 谢谢。

使用innerHTML innerText ,如果你不想让HTML)和this

<script>
function displaytext(something) {
    alert(something.innerHTML); //alerts 'testing'
    return false;
}
</script>

<a onclick="displaytext(this)">testing</a>

使用getelementbyid或类似方法获得对象后,请使用innerHTML属性。

如果只想显示文本 ,则应使用innerText

现场例子

的HTML

<a onclick="displaytext(this)">testing</a><br />
<a onclick="displayOtherText()">I'll display the div innerText</a><br />
<a onclick="displayOtherHtml()">I'll display the div innerHTML</a><br /><br />
<div id="textToDisplay"><span>Some sample</span> text here</div>

的JavaScript

<script>
    function displaytext(element){
      alert(element.innerText);
    }
    function displayOtherText(){
        alert(document.getElementById('textToDisplay').innerText)
    }
    function displayOtherHtml(){
        alert(document.getElementById('textToDisplay').innerHTML)
    }
</script>

您应该使用这样的简单函数。 但请注意,此函数采用元素ID,因此不适用于类名或元素名称。

function sayText(elId) {
    var html = document.getElementById(elId).innerHTML;
    if (html != null) alert(html)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM