简体   繁体   English

在jquery中使用兄弟姐妹的正确方法?

[英]The proper way to use siblings in jquery?

I am having an ajax function that returns updated value from the database. 我有一个从数据库返回更新值的ajax函数。 It is implemented under the click event of a certain button. 它是在某个按钮的单击事件下实现的。

DIV : DIV:

<div class="rep">
  <div class="up_arrow"></div>
  <div class="rep_count"></div>
</div>

There are about 10 same divs repeating on a page. 页面上有大约10个相同的div重复。 up_arrow is where the user will click. up_arrow是用户单击的位置。

I am trying to update the data in rep_count and also change the class of up_arrow to up_arrowed . 我正在尝试更新rep_count的数据, rep_count的类up_arrowup_arrowed

SUCCESS Function of Ajax : Ajax的成功功能:

success: function(data){
  $(this).addClass('.up_arrow').removeClass('.up_arrowed');
  $(this).css('background-position','0 40px');
  $(this).next('.rep_count').html(data);
}

This success function is a part of ajax function which is invoked on a click function and thats the reason i'm using this to refer to its siblings. 这个成功函数是ajax函数的一部分,它是在click函数上调用的,这就是我使用this来引用它的兄弟姐妹的原因。 This is not doing what i'm expecting. 这不是我所期待的。 I tried using siblings instead of next but that too is not doing the magic. 我尝试使用siblings而不是下next但这也不是在做魔术。

Thanks for your help in advance. 感谢您的帮助。

EDIT : The Click function : 编辑:点击功能:

$('.up_arrow').each(function() {
    $(this).click(function(event) {

        var resid = $(this).attr('name');

        var post_data = {
            'resid' : resid,
            '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
        };

        if(resid){
            $.ajax({
                type: 'POST',
                url: "/ci_theyaw/restaurants/plusrepo",
                data: post_data,
                success: function(data){
                    //console.log($(this).siblings('.rep_count').text());
                    $(this).addClass('.up_arrow').removeClass('.up_arrowed');
                    //$(this).css('background-position','0 40px');
                    //$(this).next('.rep_count').html(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    console.log(xhr.responseText);
                    alert(thrownError);
                }
            });
        }
    });
});

this inside the success handler does not refer the same object as it was referring outside the ajax call. 成功处理程序中的this内容不会引用与在ajax调用之外引用的相同对象。

One solution is to use a closure variable self which is referring the clicked element and then use it in the success handler. 一种解决方案是使用一个闭包变量self ,它引用被点击的元素,然后在成功处理程序中使用它。 Also there are few other changes 此外,还有其他一些变化

//there is no need to use .each() here
$('.up_arrow').click(function () {
    var resid = $(this).attr('name');
    var post_data = {
        'resid': resid,
            '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'
    };

    var self = this;
    if (resid) {
        $.ajax({
            type: 'POST',
            url: "/ci_theyaw/restaurants/plusrepo",
            data: post_data,
            success: function (data) {
                //console.log($(this).siblings('.rep_count').text());

                //you had swapped the class names here also should not use . in front of the class name, it is used only for class selector
                $(self).addClass('up_arrowed').removeClass('up_arrow');
                //$(this).css('background-position','0 40px');
                //$(this).next('.rep_count').html(data);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                console.log(xhr.responseText);
                alert(thrownError);
            }
        });
    }
});

Another solution is to use $.proxy as shown below to pass a custom context 另一种解决方案是使用$ .proxy,如下所示传递自定义上下文

success: $.proxy(function(data){
  $(this).addClass('.up_arrow').removeClass('.up_arrowed');
  $(this).css('background-position','0 40px');
  $(this).next('.rep_count').html(data);
}, this)

You need to pass the item the user clicked on to the success function. 您需要将用户单击的项目传递给成功函数。 I would change your code to this: 我会将您的代码更改为:

$('.up_arrow').click(function() {
    //you don't need an .each() loop to bind the events    

    var TheClickedItem = $(this);
    .......

    success: function(data){ 
       //now you're accessing/modifying the item that was actually clicked.
       TheClickedItem.addClass('.up_arrow').removeClass('.up_arrowed');
       TheClickedItem.....
    }

The problem is that this does not refer to the clicked element inside the success callback. 问题是this并不是指成功回调中的clicked元素。

Use the context option in $.ajax to specify what you need as this inside the success callback. 使用context中选择$.ajax可以指定你所需要的是this的成功回调中。

$.ajax({
    ...
    context: $(this), // now the clicked element will be `this` inside the callback
    ...
    success: function(data) {
        // here 'this' refers to the clicked element now
    },
    ...
});

You need to save this in onclick context, because in ajax-success function this refers to other context. 您需要在onclick上下文中保存 ,因为在ajax-success函数中, 指的是其他上下文。 You should do something like this: 你应该做这样的事情:

$('.up_arrow').on('click', function() {
    var self = this; // save this refering to <a>
    $.ajax(.....,
        success: function() {
           // this - refers to success-function context, but self - refers to 'a'-onclick handler
            $(self).addClass('.up_arrow').removeClass('.up_arrowed');
            $(self).css('background-position','0 40px');
            $(self).next('.rep_count').html(data);     
        }
    )
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM