簡體   English   中英

設置輸入的“type”屬性不適用於jQuery attr()方法

[英]Setting the “type” attribute of an input does not work with jQuery attr() method

我查看過以前的問題,但他們似乎並沒有回答我發生的事情。
在我的真實代碼中,我正在創建一個表單並添加兩個按鈕,一個用於提交,另一個用於其他功能。 為此,我將按鈕的“type”屬性設置為“submit”為一個,“按鈕”為另一個。 問題是在Chrome中,兩個按鈕都會提交表單。

表格代碼:

form = $(document.createElement('form')).attr('method', 'get').attr('action', defaults.action).appendTo(object);

按鈕代碼:

form.append(
    $(document.createElement('div')).
        attr('class', classesHash.buttonsContainer).
        append(
            $(document.createElement('button')).
                attr('type', 'submit').
                addClass(classesHash.submitButton).
                attr('title', i18n('Filter')).
                attr('value', i18n('Filter')).
                append(i18n('Filter'))
        ).
        append(
            $(document.createElement('button')).
                attr('type', 'button').
                addClass(classesHash.addButton).
                attr('title', i18n('Add filter')).
                attr('value', i18n('Add filter')).
                append(i18n('Add filter')).
            click(addFilter)
        )
);

我用這個HTML代碼做了一個更簡單的測試:

<form action="" method="get"><button id="test">test</button></form>

當Chrome找不到提交按鈕時,任何按鈕都會提交表單。

以下不起作用,表單在按鈕點擊時提交:

$('#test').attr('type', 'button');

以下工作正常,單擊按鈕時表單不提交:

document.getElementById('test').setAttribute('type', 'button');

表單和按鈕是動態生成的,我使用的是jQuery,因此attr()是最明顯的方法。 jQuery核心和Chrome的JS規范有問題嗎? 它在Firefox中運行良好。 非常感謝。

一,正確的方法:
要在這種情況下做你想做的事,請使用vanilla JavaScript解決方案, 但在IE中進行測試!


原因:
原因type不起作用是因為它在IE中失敗(在添加到DOM之后你不能對輸入的type進行處理,並且它以相同的方式處理),所以當你嘗試時jQuery會拋出一個錯誤 它在更改type屬性時專門用於<input><button>元素

如果你在控制台中查看,你會看到:

錯誤:無法更改未捕獲的類型屬性

這是一個顯示此問題的快速測試 ,請檢查控制台以查看jQuery拋出的錯誤。

使用prop而不是attr 它肯定會起作用。

請看下面的示例代碼:

$("input[name='email']").focusin(function() {
           console.log("alert");
            $('#email').prop('type','number');
});

讓我知道你對此的看法。

謝謝

所以這篇文章對我有幫助,但我的解決方案是克隆有問題的按鈕並替換它

$new = $(this).clone();
$new.attr('type','hidden');
$this_form.append($new);
$(this).remove();

我不是100%肯定你在問什么,但我認為你要求阻止在Chrome中點擊按鈕提交表單。 如果是這種情況,為什么不使用preventDefault

$("#test").click(function(e) {
  e.preventDefault();
  //more work here....
});

編輯:
我同意Nick的意見,為了做你想做的事,請采用直接的JavaScript方法。 但在這種情況下,您將屬性應用於一個沒有意義(或至少無效)的按鈕。 由於您已經在使用jQuery,為什么不正確處理它並阻止表單中按鈕單擊的默認操作?

jQuery對我來說在Chrome中運行良好...我今天拋出的所有功能都運行得很好,包括.attr()......

暫無
暫無

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

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