簡體   English   中英

在Firefox中未定義event.target,在IE中出現小錯誤

[英]event.target in not defined in Firefox and minor error in IE

我已經在Firefox上閱讀了有關事件的問題的15個不同的堆棧溢出問題。 它們並不是與我的職能密切相關,但我認為這是一個直接的問題。 我已經嘗試了所有似乎可以解決他們問題的方法,但它們都失敗了。

我的問題是在Firefox中,什么都沒有發生,這是由我的代碼順序引起的。 順序非常重要,否則會導致不必要的附加多個按鈕。 我至少理解為什么它不添加和刪除基於click函數的類。 我不明白的是我添加了var event = event || window.event; var event = event || window.event; 並嘗試了if(!event) event = window.event; 他們似乎什么也沒做,所以我什至嘗試將window.event放在任何我僅有事件發生的地方,這也不起作用。

我在IE中的問題,這至少允許我單擊並擴展這篇文章,很棒,但單擊后不會追加我的按鈕。 這不是主要問題,因為關閉文章按鈕不是生死攸關。

我的jQuery

function newsArticle() { // Articles Functionality
    $('.article').on('click', function() {
        var self = this;
        var button = $('<span />', {
            'class': 'close',
            text: 'Click to minimize article',
            on: {
                click: function (e) {
                    e.stopPropagation();
                    $(self).stop(true).toggleClass('fullArticle article');
                    $(this).remove();
                }
            }
        });
    if(!event) event = window.event;
    if($(event.target).is('.article')) {
        $(this).append(button);
    }
    else if($(event.target).parents().is('.article')) {
        $(this).append(button);
    }

    $(this).removeClass('article').addClass('fullArticle');
    });
}

newsArticle();

回答

function newsArticle() { // Articles Functionality
    $('.article').on('click', function(e) {
        var self = this;
        var button = $('<span />', {
            'class': 'close',
            text: 'Click to minimize article',
            on: {
                click: function (e) {
                    e.stopPropagation();
                    $(self).stop(true).toggleClass('fullArticle article');
                    $(this).remove();
                }
            }
        });
    if($(e.target).is('.article')) {
        $(this).append(button);
    }
    else if($(e.target).parents().is('.article')) {
        $(this).append(button);
    }

    $(this).removeClass('article').addClass('fullArticle');
    });
}

newsArticle();

的jsfiddle

如果jsfiddle沒有顯示問題,請在實時站點-> 站點上查看

只需向下滾動到整個頁腳上方和上方有4個選項卡,然后單擊“ In the News”。

如果您還有其他需要,請與我聯系,並很抱歉提出這個問題,但我一直找不到合適的答案。

使用jQuery時,您無需進行跨瀏覽器檢查( if(!event) event = window.event;等),因為jQuery會為您執行此操作。 但是,您應該在事件處理程序中將該事件作為參數接受:

$('.article').on('click', function(event) {

我喜歡使用e作為約定,以避免造成混淆:

$('.article').on('click', function(e) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM