jQuery.one()事件处理程序未执行

时间:2015-03-12 18:40:46

标签: javascript jquery html

我正在尝试使用jQuery.one()禁用一个按钮,该按钮在单击后显示树的图像。 showImage函数工作正常,但不是.one

我可以不在jquery事件处理程序中使用javascript吗?

HTML:

<div class="grove">
    <button id="plant" onclick="showImage()">Plant Orange Tree</button>
  </div>

  <div id="orange-tree-template">
    <div class="orange-tree">
      <h2>Tree Name</h2>
      <h3>etc...</h3>

的CSS:

.display-tree-big{
  background: url('../images/tree_big.jpg');
  background-repeat: no-repeat;
  height:1000px;
  width:1000px;
  border: solid black 2px;
}

#orange-tree-template { visibility: hidden; }

的javascript

function showImage() {
  var img = document.getElementById('orange-tree-template');
  img.style.visibility = 'visible';
}

$(document).ready(function() {
  $("#plant").one( "click", function() {
    document.getElementById("#plant").disabled = true;
  });
});

1 个答案:

答案 0 :(得分:3)

有几个问题。

  1. 您有一个分配给该按钮的内联onclick处理程序。这不会尊重jQuery.one方法,因此,由于错误2,您可以继续单击按钮并调用showImage

  2. 通过jQuery.one() 分配给点击事件的功能被调用,但是document.getElementById("#plant")语句不应包含#,因此按钮没有被禁用。

  3. jQuery(function($) {
      $("#plant").one("click", function() {
        // yes of course you can use JavaScript
        document.getElementById('orange-tree-template').style.visibility = 'visible';
        this.disabled = true;
      });
    });
    #orange-tree-template {
      visibility: hidden;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <button id="plant">Plant Orange Tree</button>
    
    <div id="orange-tree-template">
      TEST
    </div>

    同样jQuery.one() method不会禁用任何内容,它只是每个事件类型的每个元素最多执行一次回调。