获取 javascript 中下一个子元素,其 innerHTML 是动态值

Get the next child element in javascript whose innerHTML is dynamic value

本文关键字:innerHTML 动态 元素 javascript 下一个 获取      更新时间:2023-09-26

我有一个带有按钮的父元素,还有一个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:但是现在输出只有第一个为循环条件值。我认为 javascript 无法重新分配 x,因为值肯定在正确迭代......或者可能是输入标签无法动态获取值。欢迎对此提出任何新建议!

尝试使用nextElementSibling

x = document.getElementById("investbutton").nextElementSibling.innerHTML;

因为换行符将被视为text node.而且它不会有一个名为 innerHTML 的属性

演示


在.php

<input type="button" class="investbutton" value="Invest" onclick="InputInvest(this)">

JS:

function InputInvest(_this) {
   var x = _this.nextElementSibling.innerHTML;
   document.write(x);   
}
相关文章: