【问题标题】:Multi-line string insert using jQuery使用 jQuery 插入多行字符串
【发布时间】:2019-11-07 01:01:44
【问题描述】:
$("#addSelect").click(function() {
        $("#optionsForm").after("Hello world.");
} );

这行得通。

$("#addSelect").click(function() {
        $("#optionsForm").after("<tr>
    <td><input type="text" class="optionField" value="Options" /></td>
    <td>
        <ul class="option">
            <li><select><option>Value..</option></select></li>
        </ul>
    </td>
</tr>");
} );

这样的事情不会。

在 Chrome 中,我收到错误“Unexpected token ILLEGAL”。谷歌搜索后,我发现我的小脑袋对 javascript 和多行代码知之甚少。所以我在每行的末尾添加了“\”。然而,我现在收到错误“Unexpected identifier”。

我希望这不会像我做的那么难:)

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    将属性的所有双引号更改为单引号。

    $("#addSelect").click(function() { 
            $("#optionsForm").after("<tr> \
        <td><input type='text' class='optionField' value='Options' /></td> \
        <td> \
            <ul class='option'> \
                <li><select><option>Value..</option></select></li> \
            </ul> \
        </td> \
    </tr>"); 
    } ); 
    

    【讨论】:

      【解决方案2】:

      更简洁的方法是使用&lt;script&gt; 标签

      https://stackoverflow.com/a/12097933/1416458

      <script id="stuff_you_want" type="text/plain">
      <tr>
          <td><input type="text" class="optionField" value="Options" /></td>
          <td>
              <ul class="option">
                  <li><select><option>Value..</option></select></li>
              </ul>
          </td>
      </tr>
      </script>
      
      <script>
      
          // pure javascript
          var text = document.getElementById("stuff_you_want").innerHTML ;
      
          //or using jQuery... (document ready for safety)
          $(document).ready(function() {
      
              var text = $("#stuff_you_want").html(); 
      
          }
      
      </script>
      

      必须为html 4.0 compliance 设置内容类型。

      【讨论】:

      • 如果不设置某种类型的 会有错误
      • 谢谢!这也适用于样式标签。
      【解决方案3】:

      使用反引号`来开始和结束字符串

      $("#addSelect").click(function() {
          $("#optionsForm").after(`<tr>
          <td><input type="text" class="optionField" value="Options" /></td>
          <td>
              <ul class="option">
                  <li><select><option>Value..</option></select></li>
              </ul>
          </td>
      </tr>`);
      } );

      【讨论】:

      • 请添加一些措辞来解释你的答案。
      【解决方案4】:

      我更喜欢使用这样的东西:

      $('<tr bgcolor="#ffffe6"><td></td><td colspan="8" id="orderNotes">'
          + inputNotes.val() + '</td> <td>' + todayStamp
          + '</td> </tr>')
      

      我觉得它很干净,+ 连接让您知道我们正在使用相同的黑色,它使您可以灵活地添加变量。

      【讨论】:

        猜你喜欢
        • 2011-10-19
        • 2019-04-11
        • 2012-02-23
        • 2021-05-29
        • 1970-01-01
        • 1970-01-01
        • 2016-11-25
        • 1970-01-01
        • 2017-02-04
        相关资源
        最近更新 更多