繁体   English   中英

如何在JavaScript中正确获取这些DOM元素名称?

[英]How do I get these DOM element names right in my javascript?

我需要创建一个包含许多重复形式的页面,这些页面将更新页面上的一些div。 想象一堆标记为“ Book 1”,“ Book 2”等的书籍,您必须单击链接才能看到任何给定书籍的名称。 将有数百个。 我想用一个脚本来做。 我想我已经弄清楚了,但是我不清楚如何调用两个DOM元素。 注意我正在使用jQuery(出于与该问题无关的原因,只是相信我必须使用它)。 这是我的代码,其中有需要帮助的注释:

<html>
  <head>
    <script language="javascript" type="text/javascript"
      src="/wp-includes/js/jquery/jquery.js"></script>
  </head>

  <body>
    <p>Book 1</p>
    <form id="form001">
      <input type="hidden" name="book" value="Stranger In A Strange Land" />
      <input type="submit" name="submit" value="submit" />
    </form>
    <div id="output001"></div>

    <p>Book 2</p>
    <form id="form002">
      <input type="hidden" name="book" value="I, Robot" />
      <input type="submit" name="submit" value="submit" />
    </form>
    <div id="output002"></div>

    <script id="source" language="javascript" type="text/javascript">
      var $j = jQuery.noConflict();
      $j( "form" ).submit(function ( )
      {


        var book = ???;        //  <========= What do I put here???
        var formName = ???;    //  <========= What do I put here???


        // Below I extract the form number (e.g. “001” from “form001”) and
        // tack it on to the div name I am repopulating
        var outputDiv = '#output' + substr( formName, formName.length - 3, 3 ); 

        $j(outputDiv).html(book);
      }); 
    </script>

  </body>
</html>

我建议:

  var $j = jQuery.noConflict();

  $j( "form" ).submit(function (event) {
    // event is the form-submission event, which we
    // (probably) want to cancel, which we do by calling:
    event.preventDefault();

    // 'this' is the current <form> that's being submitted,
    // we look within that <form> to find the <input> element
    // with a name equal to 'book', and retrieve its value:
    var book = $j(this).find('input[name=book]').val();

    // we get the id of the <form> here:
    var formName = this.id;

    // here we select the appropriate element by replacing
    // the 'form' with 'output', and constructing an id-selector:
    $j('#' + formName.replace('form', 'output')).html(book);
  });

参考文献:

暂无
暂无

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

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