javascript - 在jquery插件中添加事件

标签 javascript jquery html

我想在单击特定标签时触发简单的警报。这是我的 html 代码

<html>
<head>
<script src="js/modal-load.js"></script>
<script>
    $('.modal-link').modalLoad();
</script>
</head>
....
<body>
     <div class="hblock-1 text-4 text__uppercase color-7">
           <a class="login btn btn-primary modal-link" href="/login-modal.php" data-toggle="modal" data-target="#login-modal">Log in</a>
           <a href="index.html#" class="register btn btn-primary modal-link">Register</a>
     </div>
</body>

下面是我的 jquery 插件

(function($){
     $.fn.modalLoad = function(){
         var $t = $(this);
         $t.on('click',function(){
             alert($(this).attr('href'));
         });
     };
})(jQuery);

没有任何错误,但为什么没有触发警报?还有,有没有更简单的jquery插件结构?

最佳答案

您在 head 部分编写了脚本,当执行该脚本时,目标元素 .modal-link 尚未出现在 dom 中,因此不会为这些元素初始化插件。因此,将您的脚本移至 dom ready handler .

还需要包含 jQuery 库() - 假设您已经拥有了这个库,正如您所说,没有错误。

<!-- include jQuery library-->
<script src="js/jquery.js"></script>
<script src="js/modal-load.js"></script>
<script>
    //dom ready handler
    jQuery(function($){
        $('.modal-link').modalLoad();
    })
</script>

关于javascript - 在jquery插件中添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29203642/

相关文章:

jquery - 有关 django-chunked-upload 和 jQuery-File-Upload 上传大文件的任何建议

html - 我如何在我的导航栏 CSS 中添加渐变边框

html - 如何在不更改 html 和比率的情况下裁剪图像高度(并将其居中)?

不同元素的 JavaScript 文本到语音

javascript - 在循环中更改变量

javascript - 如何撤消 "Meteor.publish"和撤消 "new Meteor.Collection"

php - 使用 PHP foreach 代码填充日历

html - 在 Z 轴上平移表单/输入

javascript - Google Closure Compiler 为新的 Web Audio API 方法提供 JSC_INEXISTENT_PROPERTY

javascript - 如何在 react 模式中将关闭按钮放置在模式窗口之外?