【问题标题】:Javascript performance when calling functions within html tags在 html 标记中调用函数时的 Javascript 性能
【发布时间】:2014-08-29 23:36:59
【问题描述】:

在 html 标记中调用“onFocus”函数时,我遇到了性能问题。我通常不会以这种方式调用函数,但我没有使用自己的代码。

使用:jQuery 1.4.2

我有两个问题:

1.) 在 html 标签中调用函数真的会降低性能吗?例如:

    <input type="text" onFocus="javascript:moveCursorToEnd(this.id)" />

2.) 当用户关注输入字段时,我想做的是将光标移动到输入的末尾。但是,目标设备没有正确反应(iPad 2 使用 Safari)。光标仍会移动到单击的位置,大约需要 10 分钟。该函数需要 15 秒才能完成。

我还没有真正找到任何干净的、跨浏览器兼容的方法来将光标移动到输入字段的末尾。

    function moveCursorToEnd(id){
      var currentElement=$("#"+id);
      var currentValue=currentElement.val();
      currentElement.focus().val(String.fromCharCode(35)).val(currentValue);
      }

然后我这样调用函数:

    <input type="text" onFocus="javascript:moveCursorToEnd(this.id)" />

有没有更好的方法来做到这一点,同时从 html 标签调用函数?

【问题讨论】:

  • 我怀疑这与内联附加的事件有关。 focus()onfocus 处理程序中触发一个新的focus 事件...
  • 就跨浏览器选项而言。根据我的经验,我发现最好的方法是将输入字段文本存储在一个变量中。清除输入字段,然后将存储的值写回输入。我知道这似乎很愚蠢,但还没有让我失望
  • onFocusjavascript: 都错了。
  • 不使用内联事件处理程序属性与性能无关,而是与cleanliness!
  • @Teemu:你说得对,它仍然可以工作,HTML 不是 XHTML。尽管如此,标准拼写是onfocus

标签: javascript jquery html


【解决方案1】:

我的解决方案:

更改了 moveCursorToEndFunction,并通过“onclick”触发该功能。出于某种原因,使用 onfocus 将 iPad 加载到屏幕键盘上大约需要 8 秒。

     function moveCursorToEnd(id){
     var currentElement=$("#"+id);
     var currentValue=currentElement.val();
     currentElement.val(String.fromCharCode(35)).val(currentValue); 
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-30
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多