2016-12-02 77 views
1

我无法使用最接近的img标签追加图像src。无法使用最接近的img标签追加图像src

当自动完成选项选择我要填充的图像该行

HTML:

<td> 
    <div> 
     <img class="participantphoto" src="images/author2.jpg" width="50" /> 
     <input placeholder="Type a letter to search students" class="form-control searchStudent formbottom" name="student[0][name]" type="text" autocomplete="off"> 
    </div> 
</td> 

JS:

$(document).on("focus keyup", "input.searchStudent", function (event) { 
    $(this).autocomplete({ 
     source: 'gdcontroller.php?action=search', 
     select: function (event, ui) { 
     console.log(ui); 
      event.preventDefault(); 
      this.value = ui.item.label; 
      // line below fails 
      $(this).parent().closest(".participantphoto").attr("src",ui.item.profile_pic); 
     }, 
     focus: function (event, ui) { 
      event.preventDefault(); 
      this.value = ui.item.label; 
     } 

    }); 
}); 
+0

$(本).parent()最接近(”。 participantphoto“).attr(”src“,ui.item.profile_pic);不管用。 –

+1

这是非常值得**的时间来阅读您尝试使用的方法(通常只需要一个小时,两个上面)的jQuery API文档。 ['closest'](http://api.query.com/closest)不会做你认为它的事情。 –

回答

2

closestinput开始将找不到img,因为img不是input祖先,它的兄弟姐妹。

,因为它是唯一img兄弟,$(this).siblings("img")发现它:

$(this).siblings("img").attr("src",ui.item.profile_pic); 

,或者如果你想使用类:

$(this).siblings(".participantphoto").attr("src",ui.item.profile_pic); 
2

那不行,因为IMG .participantphoto不是输入的父母。

你应该使用.closest('div')然后使用.find(".participantphoto")找到participantphoto类img标签去到最近的股利和最后设置属性src

$(this).closest('div').find(".participantphoto").attr("src",ui.item.profile_pic); 

或者你可以使用.siblings()代替:

$(this).siblings(".participantphoto").attr("src",ui.item.profile_pic); 

希望这有助于。