我正在为div分配值" AMD"," APPLE"。
<div id="company"></div>
但是,当我调用 outputStock()时,我的警报值会显示 HTML标记。如何获取我指定的当前字符串值?
<script>
var company = ["AMD", "APPLE"];
company.forEach(function(i) {
document.getElementById("company").innerHTML+= "<p>" + i + "</p>";
});
</script>
<script>
function outputStock() {
var stockname = document.getElementById("company").innerHTML;
alert(stockname);
}
</script>
UPDATE *:当我输出alert()时,我得
<p>AMD</p><br><hr><p>APPLE</p><br><hr>
如何摆脱警报中的html标签并获取字符串? 像这样的东西?
document.getElementById("company").innerHTML = html.replace(/<[^>]*>/g, "");
答案 0 :(得分:2)
<script>
var company = ["AMD", "APPLE"];
company.forEach(function(i) {
document.getElementById("company").innerHTML += "<p>" + i + "</p><br />" + "<hr>";
});
</script>
<script>
function outputStock() {
var name = document.getElementById("company").innerHTML;
alert(name);
}
</script>
Div标签没有任何属性,例如值。要从div标签中检索任何值,您必须使用.innerHTML
答案 1 :(得分:1)
divs内容是innerHTML而不是值,如果你改变它将返回AMD和APPLE。
var company = ["AMD", "APPLE"];
company.forEach(function(i) {
document.getElementById("company").innerHTML+= "<p>" + i + "</p>";
});
var name = document.getElementById("company").innerHTML
var noTags = name.replace('<p>' , ' ').replace('</p>' , ' ').replace('<p>' , ' ').replace('</p>' , ' ')
alert(noTags)
&#13;
<div id="company"></div>
&#13;