我在 php 代码中有一个带有按钮的父元素和一个子 div。子 div 具有要动态分配的innerHTML,并且也在输出中动态显示。
PHP 代码:
$loc = $sdid; /*get value according to some loop condition thus this value
changes as loop iterates*/
echo '<div id="parent">
<input type="button" id="investbutton" value="Invest" onclick="InputInvest()">
<div id="child">'.$loc.'</div>
</div>';
现在子级具有 $loc 变量的动态值。
单击按钮时,将调用 InputInvest():
function InputInvest()
{
var x=0;
x= document.getElementById("investbutton").nextSibling.innerHTML;
document.write(x);
}
但是输出显示“未定义” 如何解决这个错误?
编辑: 上一个问题的解决方案:
x = document.getElementById("investbutton").nextElementSibling.innerHTML;
问题2: 但现在只输出第一个 for 循环条件值。我认为 javascript 无法重新分配 x,因为这些值肯定会正确迭代...或者可能是输入标记无法动态获取值。 欢迎对此提出任何新建议!
最佳答案
x = document.getElementById("investbutton").nextElementSibling.innerHTML;
因为换行符将被视为文本节点
。而且它不会有一个名为 innerHTML
的属性。
DEMO
在.php中,
<input type="button" class="investbutton" value="Invest" onclick="InputInvest(this)">
JS:
function InputInvest(_this) {
var x = _this.nextElementSibling.innerHTML;
document.write(x);
}
关于javascript - 获取javascript中innerHTML为动态值的下一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35777355/