谁能帮我简化这个脚本?

Can anyone help me make this script simpler?

我有一个跨度和一个输入字段,当输入字段为空时,我需要它的跨度来表示 "Empty"。当我在字段中输入一些文本时,跨度会自动将 letters/numbers 添加到跨度中。如果输入值被删除,跨度将再次显示 "Empty"。

if($.trim($('#input').val()) == ''){
    $('#span').html('Empty');
}
$('#input').bind("change keyup input",function() { 
    $('#span').html($(this).val());
    if($.trim($('#input').val()) == ''){
        $('#span').html('Empty');
    }
});

我认为这可以通过一种更简单的方式实现,并希望只在一个函数中实现。这可能吗?

$('#input').on("change keyup input",function() { 
    if($.trim($('#input').val()) == ''){
        $('#span').html('Empty');
    } else {
        $('#span').html($(this).val());
    }
});

很简单:用函数设置#span元素的HTML,并在运行时和绑定到#input字段的某些事件期间执行该函数。我建议使用 .on() 而不是 .bind():

// Define function that sets html value
var updateSpan = function() {
  var v = $.trim($(this).val());
  if(v === '') {
    $('#span').html('Empty');
  } else {
    $('#span').html(v);
  }
}

// Execute function at runtime
// We use .call() so that `this` in the function refers to our input
updateSpan.call($('#input')[0]);

// Bind the function as a callback during these events, too
// The element is automatically passed as `this`
$('#input').on('change keyup input', updateSpan);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input" />
<span id="span"></span>

如果你真的喜欢混淆代码,你甚至可以将 if 语句缩短为:

var updateSpan = function() {
    var v = $.trim($(this).val());
    $('#span').html(v === '' ? 'Empty' : v);
}

是的,在我能想到的几乎所有情况下,你真的只需要 keyup。

您可以将 .bind 替换为 .on,并将触发器替换为 'keyup'。

创建函数后,您可以通过触发其中一个触发器来调用它,同时仍然使用相同的选择器。

像这样;

$('#input').on('keyup', function(){
    text = $(this).val().trim();
    if(text == ''){
        $('#span').html('Empty');
    } else {
        $('#span').html(text);
    }
}).trigger('keyup');

或者您可以定义一个函数,例如;

$.fn.emptyCheck = function(){
        return (this.val().trim() != '');
}

$.fn.emptyCheck = function(){
    text = this.val().trim();
    if(text == ''){
        $('#selector').html('Empty');
    } else {
        $('#selector').html(text);
}

然后使用

调用它
$('input').on('keyup', function(){
      if($(this).emptyCheck()){
          /* your function */ 
      }
});

$('input').on('keyup', function(){
    $(this).emptyCheck();
}

分别

这应该可以解决问题:

$('#input')
    .bind("change keyup input", function() { 
        updateSpan($(this).val());
    })
    .trigger('keyup');

function updateSpan(s) {
    $('#span').html(s.trim() == '' ? 'Empty' : s);
}

最后的.keyUp()确保事件被触发一次,所以跨度被初始化。

你可以用更少的代码来写这个。但是,我认为这是一个很好的妥协。可以一口气看完,不用解密复杂的表达式,没有冗余。