簡體   English   中英

如果調用了preventDefault(),則無法以編程方式選擇單選按鈕

[英]Cannot programmatically select radio button if preventDefault() called

我在Chrome中有一個“ catch 22”。 如果綁定到同一事件的任何其他函數調用了preventDefault()我無法以編程方式選擇click事件中的單選按鈕。

例如,我有一個單選按鈕,其父元素綁定到click事件中,在該事件中preventDefault() 如果直接單擊單選按鈕,則不會選中它。 這是預料之中的。 但是,實際上,我需要選擇單選按鈕,因此在代碼中,我嘗試在綁定到click事件的另一個函數中檢查它: $(this).prop('checked', true);

奇怪的是,這行不通,並且我無法刪除對preventDefault()的調用或禁用傳播,因為它在我需要運行的第三方代碼中。

這是錯誤嗎? 有建議的解決方法嗎?

這是一個示例: http : //jsfiddle.net/LnLuk4st/

更新:

我已經嘗試過@RGraham的建議。 他的示例顯然有效,但奇怪的是,在我的代碼上下文中它不起作用 @RGraham的代碼存在語法錯誤,這使其似乎正常工作。

這里是一些上下文:

// Remember kendo tab
$(".k-tabstrip").each(function () {
    var $tabStrip = $(this);
    var $tabs = $tabStrip.find(".k-tabstrip-items .k-item");
    var tabCookie = "Current_Tab_" + $tabStrip.attr("id");

    // On tab change, set cookie
    $tabs.click(function () {
        createCookie(tabCookie, $(this).attr("aria-controls"), 1);
        $tabStrip.parent().css({ 'min-height': $tabStrip.parent().height() });


        if ($(this).is('input')) { // Doesn't eval to true, 'this' is always a '.k-item'.
            $(this).prop("checked", true);
        } else {
            // Never works if the input is clicked directly
            $(this).find('input').prop("checked", true);
        }


    });

    // @RGraham's suggestion...
    $tabs.on('click', 'input', function() {
        $(this).prop("checked", true); // Line reached but doesn't work either :(
    });

    // If cookie set, select tab
    var tab = readCookie(tabCookie);

    if (tab) {
        $tabs.each(function () {
            if ($(this).attr("aria-controls") == tab) {
                $(this).click();
            }
        });
    }
});

我仍然認為此行為是一個錯誤,但是我找到了一種解決方法。

直接捕獲單選按鈕的單擊,防止傳播,然后以編程方式單擊單選按鈕的父級。 這允許運行第三方代碼,而無需將單選按鈕應用preventDefault

    // preventDefault bug fix.
    $tabs.find("input").click(function (e) {
        e.stopPropagation();
        $(this).parent().click();
    });

暫無
暫無

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

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