【问题标题】:undefined variable error in jqueryjquery中未定义的变量错误
【发布时间】:2015-03-02 19:28:51
【问题描述】:

我有这段代码,我想在将由 jquery 创建的元素中显示 il,但 il 未定义: 这是代码:

<script>
$(document).ready(function(){
    var il = 1 ;
    $("#btn1").click(function(){
        $("p").append(" <b>Appended text</b>.");
    });
    $("#btn2").click(function(){
        $("ol").append("<li>Appended item " + il + " </li>");
var il = il + 1;
    });
});
</script>


<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>

这是输出:

List item 1
List item 2
List item 3
Appended item undefined
Appended item undefined

【问题讨论】:

标签: jquery variables global-variables undefined


【解决方案1】:

只需使用 il++。

 $(document).ready(function(){
    var il = 1 ;
    $("#btn1").click(function(){
        $("p").append(" <b>Appended text</b>.");
    });
    $("#btn2").click(function(){
        $("ol").append("<li>Appended item " + il + " </li>");
        il++;
    });
});

【讨论】:

    【解决方案2】:

    只需从var il = il + 1; 中删除var。

    var 仅用于新变量声明。

    $(document).ready(function(){
        var il = 1 ;
        $("#btn1").click(function(){
            $("p").append(" <b>Appended text</b>.");
        });
        $("#btn2").click(function(){
            $("ol").append("<li>Appended item " + il + " </li>");
            il = il + 1;
        });
    });
    

    JSFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      相关资源
      最近更新 更多