为什么我的动态javascript高亮表单中断

Why does my dynamic javascript highlight form break?

本文关键字:表单 中断 高亮 javascript 我的 动态 为什么      更新时间:2023-09-26

我一直在尝试构建一个简单的html表单,通过在表单的keyup(使用jquery)的span中包装它,在页面上突出显示黄色文本。

它工作得很好,直到我在键盘上退格以完全清除表单的内容,然后它停止工作。我创建了一个快速代码依赖来演示我的问题:

http://codepen.io/liamtarpey/pen/KefCx

这可能是一个非常简单的修复,但我不能得到我的头周围出了什么问题,有人知道是什么问题吗?

我真的很想使用'body'或'html'选择器而不是'*',因为它也会影响我的页面头部,但我不能让它与这些中的任何一个一起工作。

HTML:

<form>
<input type="text" id="searchfor"/>
</form>
<!-- The below is just a test to check the value of the input is being returned -->
<span>Value of form: </span><span id="test"></span>
<div>
  <h3>example text here</h3>
</div>
jQuery:

$("#searchfor").on("keyup change", function() {
  // store value in a variable
  value = this.value;
  // unwrap span from previous search
  $("span[id^='highlightspan']").contents().unwrap();
  // wrap span around inputted text
  $("*").each(function() { 
    if($(this).children().length==0) { 
      $(this).html($(this).html().replace(value, '<span id="highlightspan" style="background:yellow;">' + value + '</span>')); 
    } 
  });
  $("#test").html(value);

});

在打开highlightspan元素后删除它们:

  $("span[id^='highlightspan']").contents().unwrap();
  $("span[id^='highlightspan']").remove();

这将防止DOM上重复的id,但是最好只是将highlightspan作为一个类。

http://codepen.io/anon/pen/rIujD

Fiddle

if (value === '') {
    $('#highlightspan').remove();
}  

您需要删除highlightspan,因此再次在此代码中添加$(this).html($(this).html().replace(value, '<span id="highlightspan" style="background:yellow;">' + value + '</span>'));