如何选择正确的'这个'选择器?

时间:2015-10-30 13:36:27

标签: javascript jquery this

JSFIDDLE:http://jsfiddle.net/nqsfoqzz/10/

我无法弄清楚下面代码中this选择器的内容。如果我调用函数removeAndClose(elem);如点击事件结束时所示(当前已注释掉),$(this)的值是正确的,即.removeleg。但我需要根据弹出窗口中的click事件来控制removeAndClose()函数,这是click事件中$ noticeMessage的原因,以及函数noticePopup()的原因。我已将removeAndClose(elem)添加到Confirm按钮,这是this问题出现的地方。

因为我在$ noticeMessage elem is undefined中使用了removeAndClose()函数。

我已经整理了一个显示问题的jsfiddle:http://jsfiddle.net/nqsfoqzz/10/要查看CONFIRM按钮,请先点击“添加LEG'按钮。然后点击“删除腿”'来自新添加的元素。然后,您应该看到弹出窗口以确认或取消删除。

主要点击事件:

    $('.missionlegswrapper').on('click', '.removeleg', function(e){
        e.preventDefault();

        var elem = $(this);

        // Notice Message
        $noticeMessage = 
                '<div>' + 
                    '<div>Are you sure you want to remove this leg? All the information you\'ve entered will be lost.</div>' + 
                    '<div>' + 
                        '<a href="javascript:void(0);" class="button confirm green" onClick="removeAndClose(elem);">Confirm</a>' + 
                        '<a href="javascript:void(0);" class="button cancel red" onClick="closePopup();">Cancel</a>' + 
                    '</div>' + 

                    '<div class="clear"></div>' + 
                '</div>';

        // Notice Popup
        noticePopup('error',$noticeMessage);

        //removeAndClose(elem);
    });

附加功能:

    /**
      * Notice Popup Function
      * messageType: The message to be entered into the popup
      * message: error, notice, warning (services as class name identifier)
      */
    function noticePopup(messagetype,message){

        // Append Backdrop to Body
        $('body').append('<div class="noticepopupbackdrop"></div>');

        // Append Popup to Body
        $('body').append(
            '<div class="noticepopup ' + messagetype + '">' + 
                '<div class="noticepopup_outer">' + 
                    '<div class="noticepopup_inner">' + 
                        '<div class="noticepopup_header">' + 
                            '<span>Attention</span>' + 
                            '<div class="noticeclosebttn"></div>' + 
                        '</div>' + 
                        '<div class="noticepopup_content">' + 
                            '<div class="noticepopupcontent_inner">' + 

                                message + 

                                '<div class="clear"></div>' + 
                            '</div>' + 

                            '<div class="clear"></div>' + 
                        '</div>' + 

                        '<div class="clear"></div>' + 
                    '</div>' + 

                    '<div class="clear"></div>' + 
                '</div>' + 

                '<div class="clear"></div>' + 
            '</div>'
        );

        // Initial Open
        $('div.noticepopupbackdrop').fadeIn(150);
        $('div.noticepopup').css({display: 'block'}).animate({top: '50%', opacity: '1.00'}, 300);

        // Grab Width and Height and Center Popup on Page Load
        popupWidthHeight();

        // On Resize
        $(window).on('resize', function(){

            // Grab Width and Height and Center Popup on Resize
            popupWidthHeight();
        });

        // On Click Close
        $('div.noticepopupbackdrop,div.noticeclosebttn').on('click', function(){
            closePopup();
        });
    }


    /**
      * Close Popup Function
      */
    function closePopup(){
        $('div.noticepopup').fadeOut(150);
        $('div.noticepopupbackdrop').fadeOut(175);

        setTimeout(function(){
            $('div.noticepopupbackdrop,div.noticepopup').remove();
        }, 350);
    }


    /**
      * Get Notice Popup Width and Height Function
      */
    function popupWidthHeight(){

        var noticeWidth = $('div.noticepopup').width();
        var noticeHeight = $('div.noticepopup').height();

        $('div.noticepopup').css({marginTop: -(noticeHeight / 2), marginLeft: -(noticeWidth / 2) });
    }


    /**
      * Close Popup Notice and Remove Mission Leg
      */
    function removeAndClose(thisObj){
        thisObj.closest('.missionlegitem').remove();

        console.log(thisObj);

        // Close Popup
        var popupCloseTime = setTimeout(function(){
            closePopup();
        },25);
    }

1 个答案:

答案 0 :(得分:1)

下面的代码可以做得更漂亮和抽象,但实质上你可以将HTML设计与功能行为分开,类似于下面的内容。

我只是稍微将HTML与功能代码分开,但是为了更好的可重用性,我可以自由地进一步发展。

您的任务Leg Wrapper点击事件代码可能会更改为:

// Data Entry Form Remove Leg
$('.missionlegswrapper').on('click', '.removeleg', function(e){
    e.preventDefault();

    var elem = $(this);

    // Notice Message
    // Removed in-line click events
    // Added identifiers through use of data-id to each link
    $noticeMessage = 
        '<div>' + 
        '<div>Are you sure you want to remove this leg? All the information you\'ve entered will be lost.</div>' + 
        '<div>' + 
        '<a data-id="notice-message-confirm" href="javascript:void(0);" class="button confirm green">Confirm</a>' + 
        '<a data-id="notice-message-cancel" href="javascript:void(0);" class="button cancel red">Cancel</a>' + 
        '</div>' + 

        '<div class="clear"></div>' + 
        '</div>';

    // Add click event handlers in JavaScript instead
    // Assigning the "this" context through the use of "bind"
    $(document).on('click', '[data-id="notice-message-confirm"]', removeAndClose.bind(this));
    $(document).on('click', '[data-id="notice-message-cancel"]', closePopup);

    // Notice Popup
    noticePopup('error',$noticeMessage);

    //removeAndClose(elem);
});

由于removeAndClose()

,您的bind(this)方法现在位于所点击的链接的上下文中
/**
  * Close Popup Notice and Remove Mission Leg
  */
function removeAndClose(){
    console.log(this);
    $(this).closest('.missionlegitem').remove();

    // Close Popup
    var popupCloseTime = setTimeout(function(){
        closePopup();
    },25);
}

参见工作示例here

上面的代码仍然是&#34;凌乱&#34;并且你可以将每个通知包装在它自己的对象中,并且每个通知都管理它自己的事件处理等。