gpt4 book ai didi

javascript - jquery 帮助选择 parent

转载 作者:行者123 更新时间:2023-11-29 20:21:32 24 4
gpt4 key购买 nike

我有这个 HTML

<li>
<a rel="1" href="/jobwall/job/1">
<img src="http://lcl.moovjob.com/media/images/employers/simonainleydotinfo.jpg">
</a>
</li>

我有这个javascript

$('ul#jobs li a').mouseenter(function(){
$(this).parent().addClass('active');
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
$(this).parent($(this)).addClass('added');
}
});
}).mouseleave(function(){
$('#wrapper').append('Leave');
});

在鼠标输入时,我想添加一个类 li,它包含上面有 mouseenter 事件的 a,但是我无法让它在 mouseenter 上添加类。

最佳答案

您有两次调用 .addClass()。你说的是哪一个?

第一个应该可以。

第二个不会,因为 this 的值在 success: 回调中发生了变化。您可以将其缓存在一个变量中并在其中引用它。

$('ul#jobs li a').mouseenter(function(){

// cache the parent here, because "this" will have different
// meaning in the callback
var $parent = $(this).parent().addClass('active');
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {

// Inside here, "this" no longer references the DOM element
$parent.addClass('added'); // reference the parent you cached
}
});
}).mouseleave(function(){
$('#wrapper').append('Leave');
});

另一种选择是设置 AJAX 调用的 context: 属性。

$.ajax({
type: 'POST',
context: this, // set the context to the current "this" for the callback
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
$(this).parent().addClass('added');
}
});

另一个选择是 use $.proxy()保留 this 的值。

$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success: $.proxy( function(html) { // Have $.proxy return a function
$(this).parent().addClass('added'); // with the proper "this"
}, this )
});

关于javascript - jquery 帮助选择 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3773922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com