如何在文件准备好的情况下点击事件...?

时间:2017-05-11 15:21:13

标签: javascript jquery triggers click document-ready

单选按钮

<input name="radio-choice-t-6" class="qololbl" id="radio-choice-t-6a" value="qolo" checked="checked" type="radio">
<label for="radio-choice-t-6a" style="border: 1px solid #2d5f7c;width:90px;border-bottom-left-radius:4px;border-top-left-radius:4px;font-family:Noto Sans;">Toast</label>

$(document).ready(function (e) {

    $('.qololbl').trigger('click'); 

    $(".qololbl").click(function(){
        alert("Hi");
     });
});

如何在文档准备好的情况下触发qololbl click事件。这段代码不起作用为什么..? 提前致谢。 帮助我

1 个答案:

答案 0 :(得分:10)

使用.click()代替.trigger()。并在事件处理者声明之后提出。

$(document).ready(function (e) {

    $(".qololbl").click(function(){
        alert("Hi");
     });
     
     $('.qololbl').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="radio-choice-t-6" class="qololbl" id="radio-choice-t-6a" value="qolo" checked="checked" type="radio">
<label for="radio-choice-t-6a" style="border: 1px solid #2d5f7c;width:90px;border-bottom-left-radius:4px;border-top-left-radius:4px;font-family:Noto Sans;">Toast</label>

替代方案(由pratik-gaikwad建议)

$(document).ready(function (e) {

    $(".qololbl").on('click', function(){
        alert("Hi");
     });
     
     $('.qololbl').trigger('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="radio-choice-t-6" class="qololbl" id="radio-choice-t-6a" value="qolo" checked="checked" type="radio">
<label for="radio-choice-t-6a" style="border: 1px solid #2d5f7c;width:90px;border-bottom-left-radius:4px;border-top-left-radius:4px;font-family:Noto Sans;">Toast</label>