jQuery 多个事件,包括一个 IF 语句

jQuery multiple events including an IF statement

有人知道如何在 jQuery 中合并这两个事件吗?

我能得到的最接近的是有 2 个重复的脚本来响应 2 个不同的事件,在我看来这绝对是糟糕的。但这是我目前能想到的唯一方法。这两个脚本做完全相同的事情(或者实际上做很多事情)。我知道 jQuery 可以选择将多个事件处理程序添加到同一元素,但如果其中一个事件包含 if 条件,这将如何工作?

当用户单击单选组中的单选按钮时运行:

$(document).ready(function() {

  // When radio button is clicked
  $("input[name='select']").click(function() {
    var select = $("input[name='select']:checked").val();
    $.ajax({
      type: "POST",
      url: "script.class.php",
      data: { select: select },
      cache: false,
      success: function(data) {
        // A lot of things will happen here...
      },
      error: function(xhr, status, error) {
        console.error(xhr);
      }
    });
  });     
});

如果单选组已经选择了单选按钮,则运行此命令:

$(document).ready(function() {

  // If value is already present
  if ($("input[name='select']:checked").val()) {
    var select = $("input[name='select']:checked").val();
    $.ajax({
      type: "POST",
      url: "script.class.php",
      data: { select: select },
      cache: false,
      success: function(data) {
        // The same things as in the previous script will also happen here...
      },
      error: function(xhr, status, error) {
        console.error(xhr);
      }
    });
  }
});

将所有常用代码放在一个函数中,然后调用它

$(document).ready(function() {

  // When radio button is clicked
  $("input[name='select']").click(commonCode);
  if ($("input[name='select']:checked").val()) {
    commonCode();
  }
  function commonCode(){  
    var select = $("input[name='select']:checked").val();
    $.ajax({
      type: "POST",
      url: "script.class.php",
      data: { select: select },
      cache: false,
      success: function(data) {
        // A lot of things will happen here...
      },
      error: function(xhr, status, error) {
        console.error(xhr);
      }
    });
  }     
});