Jquery .prev()意外结果

Jquery .prev() unintended results

本文关键字:意外 结果 prev Jquery      更新时间:2023-09-26

我有这些内容可编辑的字段,旁边有一个小铅笔图标,给用户一些视觉反馈。但是,当用户单击铅笔时,我正在使用jquery应用的一些其他元素获得焦点。期望的结果是,jquery应该找到prev元素,并关注

html

 //these divs are all over the page..
  <div>
    <span class="editable" contenteditable="true">my title </span>
    <i class="fa fa-pencil"></i>
  </div>
jquery

//focus the prev .editable match, not any of the other .editables within the dom   
$( ".fa-pencil" ).click(function() {
    $( ".fa-pencil" ).prev( ".editable" ).focus();
});

你需要引用你正在点击的元素。

$( ".fa-pencil" ).click(function() {
    $(this).prev( ".editable" ).focus();
});

对于$(".fa-pencil").prev( ".editable" ).focus();,您可以引用该类的每个元素并找到它的兄弟元素。

用这个替换jquery的内部选择器

(美元).prev (.editable)…

通过这种方式,jquery将开始从点击的图标中寻找可编辑的span。现在你正在寻找"文档范围"