Jquery:在悬停时更改占位符文本,在悬停后重新添加原始文本



我创建了一个没有典型外观(边框)的文本输入部分。它们都具有占位符属性。当用户将鼠标悬停在每个输入上时,我希望占位符文本发生变化。一旦他们离开输入区域,我希望重新添加原始占位符文本。我已经成功地在悬停时将备用占位符文本就位,并且我尝试使用 data 方法重新添加原始占位符文本。

标记:

<input type="text" class="inline-edit" placeholder="Id Number" data-ph="Id Number">
<input type="text" class="inline-edit" placeholder="First Name" data-ph="First Name">
<input type="text" class="inline-edit" placeholder="Last Name" data-ph="Last Name">
Etc..

Jquery:

$(function(){
  $('.inline-edit').mouseover(function(){
    $(this).attr('placeholder', 'edit');
  });
  $('.inline-edit').mouseout(function(){
    var holder = $('.inline-edit').data('ph');
    $(this).attr('placeholder', holder);
  });
})

正在发生的事情是jquery正在获取第一个数据属性(data-ph="Id Number"),并将占位符文本替换为所有输入的值。

悬停后的标记:

<input type="text" class="inline-edit" placeholder="Id Number" data-ph="Id Number">
<input type="text" class="inline-edit" placeholder="Id Number" data-ph="First Name">
<input type="text" class="inline-edit" placeholder="Id Number" data-ph="Last Name">
Etc..

我已经搜索了很远很远的范围,除了在焦点上更改文本之外,我找不到类似的情况。据我了解,模糊方法对我完成这项任务没有帮助。我希望我对这个问题的解释是清楚的,并提前感谢您。

问题出在您的holder变量上。它可能像这样工作:

var holder = $(this).data('ph');

更新

或者你可以执行以下操作:

$(function(){
  $('.inline-edit').mouseover(function(){
    //gets the current placeholder
    this.holder=$(this).attr('placeholder');
    $(this).attr('placeholder', 'edit');
  });
  $('.inline-edit').mouseout(function(){
    $(this).attr('placeholder', this.holder); //sets it back to the initial value
  });
})

无需使用其他内联属性。

避免进一步的问题,请考虑使用$.focus()$.blur()

最新更新