简体   繁体   English

单击按钮时调用jQuery函数

[英]Call a jQuery function when a button is being clicked

I'm trying to set jQuery a function on its own, and call the function when a click event triggers. 我正在尝试自行设置jQuery一个函数,并在click事件触发时调用该函数。 Here's the code I've managed to come up with: 这是我设法提供的代码:

HTML: HTML:

<input type="text" class="form-control email_input" name='email' id="reserve_email_1" placeholder="Email">
                <span class='input-group-btn'>

                  <button type="submit" id="subscribe_1" class="btn btn-success subscribe_button">Send now</button>

</span>

JS: JS:

$(document).ready(function(){
$('.subscribe_button').click(function(){
$.fn.Subscribe();
 });

 $.fn.Subscribe = function(){ 
  var email = $(this).parent().siblings('.email_input').val();
  alert(email);
} 

});

But no matter what values I have in the email input, it would not pop up in the alert. 但是,无论我在电子邮件输入中使用什么值,它都不会在警报中弹出。 I tested and don't think it's the wrong traversing order, but rather the first function failed to call the 2nd function. 我进行了测试,并不认为这是错误的遍历顺序,但是第一个函数未能调用第二个函数。 Any advice on why it would happen? 有什么建议为什么会发生?

Best, 最好,

Subscribe is a plugin method, so you need to invoke it like a jQuery plugin like(so that the method will get proper context value for this ) Subscribe是一个插件方法,因此您需要像jQuery插件一样调用它(这样该方法将this获得适当的上下文值)

$('.subscribe_button').click(function () {
    $(this).Subscribe();
});

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM