如果选中复选框,则触发单击

时间:2016-11-01 21:50:05

标签: jquery html forms

我想要实现的是一个复选框,如果选中它然后它会触发一个jquery事件,其中点击时带有id paybox按钮的按钮也会点击id为mc-embedded-subscribe的按钮

我想出的jQuery是:

<script type='text/javascript'>
$('#notifyme').live('change', function(){
    if($(this).is(':checked')){
       $("#paybox-button").bind("click", (function () {
    $("#mc-embedded-subscribe").trigger("click");
    }));
    }
});
</script>

我的HTML是

<a class="paybox-button" href="#" id="paybox-button" onclick="return    paybox_continue(this);">'.__('Continue', 'paybox').'</a>
<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button" style="display: none;" />
<input name="_mc4wp_lists[]" type="checkbox" value="c62e5af6c6" checked id="notifyme"> Check this box to be notified by email when we publish new content.<br />&nbsp; &nbsp;

2 个答案:

答案 0 :(得分:0)

live已被弃用(JQuery 1.7)

bind已被弃用(JQuery 3.0)

将其更改为:

$('#notifyme').change(function(){
    if($(this).is(':checked')){
       $("#paybox-button").on("click", (function () {
          $("#mc-embedded-subscribe").trigger("click");
       }));
    }
    else
    {
      $('#paybox-button').off('click');
    }
});

答案 1 :(得分:0)

这是你要找的吗?当我选中复选框时,当您点击#mc-embedded-subscribe时,它会触发#paybox-button上的点击事件,这就是我解释您要尝试做的事情。

附注 - 使用onclick=以及jQuery点击处理程序会很匆忙。因此,我从onclick

中删除了#paybox-button属性

$(function () {
  function handleChange ($trigger) {
    if($trigger.is(':checked')){
      // namespace the event so we can .off() it very easily
      $("#paybox-button").on("click.notify", (function () {
        $("#mc-embedded-subscribe").trigger("click");
      }));
    }
    else {
      // remove the namespaced event handler
      $("#paybox-button").off("click.notify");
    }
  }
  handleChange($("#notifyme"));
  
  $('#notifyme').on('change', function(){
    handleChange($(this));
  });
  // set up dummy event handler so we know when the hidden button
  // gets clicked
  $("#mc-embedded-subscribe").on("click", function () {
    alert("subscribed!");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="paybox-button" href="#" id="paybox-button">'.__('Continue', 'paybox').'</a>
<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button" style="display: none;" />
<input name="_mc4wp_lists[]" type="checkbox" value="c62e5af6c6" checked id="notifyme"> Check this box to be notified by email when we publish new content.<br />&nbsp; &nbsp;