提供div可以回退的默认文本

时间:2019-01-31 09:12:39

标签: javascript html

div为空的情况下,如何使我的input的内容回到更改之前的状态?我这样做是因为人们可能会擦除input,而div也将是空的。

let target = $('#toBeChanged');
let tracked = $('#tracked');

tracked.keyup(function() {
  if (!tracked.val()) {
    //I want it to fall back to 'Default Text'
    return;
  }
  
  target.text(tracked.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id = "tracked" type = "text">

<div id = "toBeChanged">
  Default Text
</div>

4 个答案:

答案 0 :(得分:2)

让我们使用CSS,每当div得到empty时,都要显示before的内容。

因此,不再需要检查input的值。如果value的长度> 0,则div不再没有empty且将显示value,并且如果value为零(''div将是empty,而CSS将显示默认文本。

let target = $('#toBeChanged');
let tracked = $('#tracked');

tracked.keyup(function() {
  target.text(tracked.val());
});
#toBeChanged:empty::before {
  content: 'Default Text';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id = "tracked" type = "text">

<div id = "toBeChanged"></div>

希望能提供帮助。

答案 1 :(得分:1)

您可以将其存储在变量中,然后在没有提供有效文本的情况下使用它:

let defaultText = 'Default Text';
let target = $('#toBeChanged');
let tracked = $('#tracked');

tracked.keyup(function() {
  if (!tracked.val()) {
    //I want it to fall back to 'Default Text'
    target.text(defaultText);
    return;
  }
  
  target.text(tracked.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id = "tracked" type = "text">

<div id = "toBeChanged">
  Default Text
</div>

答案 2 :(得分:1)

在初始化时存储该值。

let target = $('#toBeChanged');
let tracked = $('#tracked');
let defaultText = target.text();

tracked.keyup(function() {
  if (!tracked.val()) {
    //I want it to fall back to 'Default Text'
    target.text(defaultText);
    return;
  }

  target.text(tracked.val());
});

答案 3 :(得分:0)

只需在您的target.text("Default text");语句中调用if。参见此codepen

let target = $('#toBeChanged');
let tracked = $('#tracked');

tracked.keyup(function() {
  if (!tracked.val()) {
    //I want it to fall back to 'Default Text'
    target.text("Default Text");
    return;
  }

  target.text(tracked.val());
});