У мене є цей HTML
<li>
<a rel="1" href="/jobwall/job/1">
<img src="/images/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");
});
На миші введіть я бажаю додати клас, який утримує той, що має подія mouseenter на ньому, однак я не можу отримати його, щоб додати клас на mouseenter.
Відповіді:
1 для відповіді № 1Ваша ця внутрішня подія успіху буде вікном, а не елементом прив'язки. Візьміть посилання на якорі за межами виклику .ajax і використовуйте його в події успіху.
$("ul#jobs li a").mouseenter(function(){
var $this = $(this);
$this.parent().addClass("active");
$.ajax({
type: "POST",
url: "/jobwall/job_tooltip",
data: "employer_id="+$(this).attr("rel"),
success:function(html) {
$this.parent().addClass("added");
}
});
}).mouseleave(function(){
$("#wrapper").append("Leave");
});
2 для відповіді № 2
Ви маєте два виклики .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");
});
Інший варіант - встановити context:
властивості виклику AJAX.
$.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");
}
});
І ще один варіант використовувати $.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 )
});
0 для відповіді № 3
Ви неправильно називаєте parent
метод
Змінити його на
$(this).parent()
0 для відповіді № 4
Спробуй
$(this).closest("li").addClass("added");
Або просто
$(this).parent().addClass("added");