在$ {document).ready上应用onclick函数

时间:2018-09-27 02:51:53

标签: javascript html css

我有3个div,它在页面加载时依次淡出,就像在此链接上一样: http://jsfiddle.net/x4qjscgv/6/但是,我希望用户单击按钮后才能执行淡入淡出功能。我尝试使用该功能:document.getElementById,但似乎无法正常工作。

查看下面的完整代码:

<html>

<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>

$(document).ready(function() {
  $('.word1, .word2, .word3').each(function(fadeIn) {
    $(this).delay(fadeIn * 500).fadeIn(1000);
  });
});

document.getElementById('btn').onclick = function(e)

</script>

<style>
    #chat {
      display: none;
    }
</style>

</head>

<body>

<button id="btn"> fade divs </button>

<div id="chat" class="word1">Word 1</div>
<div id="chat" class="word2">Word 2</div>
<div id="chat" class="word3">Word 3</div>


<div id="" class="">Word 4</div>

</body>

</html>

4 个答案:

答案 0 :(得分:0)

此行确实选择了#btn,但是由于函数声明不完整,因此它不执行任何操作: document.getElementById('btn').onclick = function(e)

您必须像下面这样包含函数的动作:

document.getElementById('btn').onclick = function(e){
    // add function within curly braces.
}

值得注意的是,eEvent object。尝试添加console.log('test')并检查控制台(通常可通过右键单击>“检查”访问)以查看消息。

答案 1 :(得分:0)

您使用的onclick函数确实没有任何作用,因为您没有用它包装您的淡入代码。如果您已经在使用jquery,请尝试使用click event handler,如下所示:

$(document).ready(function() {
    $('#btn').click( function () {
        $('.word1, .word2, .word3').each(function(fadeIn) {
            $(this).delay(fadeIn * 500).fadeIn(1000);
        });
    });
});

答案 2 :(得分:0)

修改您的示例:

def repeat_elem (values, index, num_times):
    # this function returns a new list in which the element of 'values' 
    # at position 'index' has been repeated 'num_times' times
    return values[:index] + values[index]*(num_times - 1) + values[index+1:]

答案 3 :(得分:0)

您可以按照我的示例进行操作。但是请注意,id只是一个实例,而class可以有很多实例!

  $(document).ready(function() {
    $('.word1, .word2, .word3').each(function(fadeIn) {
      $(this).delay(fadeIn * 500).fadeIn(1000);
    });
  });
  
  $("#btn").on('click', function(e){
    $('.word1, .word2, .word3').each(function(fadeIn) {
      $(this).delay(fadeIn * 500).fadeIn(1000);
    });
  });
  $("#btnhide").on('click', function(e){
    $('.chat').hide();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<style>
  .chat {
    display: none;
  }
</style>
</head>
<body>

  <button id="btn"> fade divs </button> <button id="btnhide"> hide divs</button>
  
  <div class="chat word1">Word 1</div>
  <div class="chat word2">Word 2</div>
  <div class="chat word3">Word 3</div>
  
  
  <div id="" class="">Word 4</div>
</body>

相关问题