javascript函数只适用于第一个元素

javascript function only works with first element

本文关键字:第一个 元素 适用于 函数 javascript      更新时间:2023-09-26

我有一个xsl文件,我可以让它在点击函数中显示标题,但我只能显示第一个标题,其他标题保持隐藏,无论哪个按钮调用函数,第一个标题都会显示。该功能在按下按钮后也不会隐藏按钮,所以该功能和特定行一定有问题吗?此外,我将用internet explorer打开这个。。

    <script language="javascript">
      function ShowTitle(title, btn)
      {
      document.getElementById("title").style.display = 'inline'
      title.style.display = 'inline'
      btn.style.display = 'none'
      }
    </script>
    <body>
      <xsl:for-each select="/questions/question/movie[position() >1]">
        <div style="background-color:tan;color:black;">
          <span style="font-weight:bold">In What Movie Did They Say:
            <xsl:value-of select="quote"/> -
          </span>
          <input type="button" value="Show title" onclick="ShowTitle('title', this)"></input>
          <span id="title" style="display:none">
          <xsl:value-of select="title"/></span>
        </div>
        <div style="margin-bottom:1em;font-size:15pt">
        </div>
        <br/>
      </xsl:for-each>

正如OJay所说,问题是当XSL使用id生成多个元素时,您正试图通过id检索元素。

你应该更改你的html 的这一部分

<div style="background-color:tan;color:black;">
  <span style="font-weight:bold">In What Movie Did They Say:
    <xsl:value-of select="quote"/> -
  </span>
  <input type="button" value="Show title" onclick="ShowTitle(this)"></input>
  <span class="title" style="display:none">
    <xsl:value-of select="title"/>
  </span>
</div>

然后,您可以按如下方式更新ShowTitle方法:

function ShowTitle(btn) {
    // get the btn's parent element. In this case the div
    var btnParentDiv = btn.parentElement;  
    // use getElementsByClassName to retrieve the title
    // getElementsByClassName returns an array of elements. 
    // In this case this is an array of length == 1
    // we're just interested in the first result, so get it immediately
    var divTitleElement = btnParentDiv.getElementsByClassName('title')[0];

    // Set the selected element to be visible
    divTitleElement.style.display = 'inline'
    // hide the button as before        
    btn.style.display = 'none'
}

这个代码可以缩短,但我已经分解了一些步骤来包括解释