簡體   English   中英

通過javascript更改輸入類型不適用於Chrome,但適用於IE,為什么?

[英]Change of input type by javascript don't work with Chrome but with IE, why?

該代碼在IE(11.0.9600.17937)中有效,但在Chrome(44.0.2403.157)中無效,我不知道為什么。 我只是關於JavaScript的新手,所以可能我做錯了所有事情,請耐心等待。 希望您能收到一些有關如何使它起作用的提示。

custom.js

// Change type of a form input
function chngtype(input,form,index)
{
    document.forms[form].item(index).type = input;
}

test.php的

<!DOCTYPE html>
<html lang="sv-se">
<head>
<title>test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="lib_styles/custom.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="lib_js/custom.js"></script>
</head>
<body>
<form action="test.php" method="post" name="test" role="form" id="test">
    <div class="form-group">
        <label for="alias">Test</label>
        <input type="text" name="test" class="form-control" id="test" value="Testar">
    </div>
    <button type="button" class="btn btn-default btn-sm" onClick="chngtype('submit','test',1)">Script submit</button>
    <button type="submit" class="btn btn-success">Normal submit</button>
</form>
</body>
</html>

問題是我希望在表單中有2個提交按鈕,但只有一個默認按鈕。 我的解決方案是只讓一個成為type =“ submit”,另一個成為type =“ button”。 這樣,如果用戶在表單中按Enter,它將始終使用默認提交。 如果用戶單擊非默認的提交按鈕,我將使用onClick來運行JavaScript,該JavaScript會將類型從按鈕更改為提交,但只能在IE中使用,而不能在Chrom中使用(尚未測試Firefox,Opera或Safari)。

有人可以告訴我原因,甚至可以為我指出解決方案嗎?

長期的解決方法是找到另一種方法,但是,如果您有很多使用此方法的代碼,則可以嘗試以下方法使您的代碼跨瀏覽器兼容:

if (typeof oForm.item == 'undefined')
{
    oForm.item=function(fieldName)
    {
        out=[];
        for (i=0; i < this.length; i++)
        {
            switch (this[i].name)
            {
                case fieldName:
                    out[out.length]=this[i];
            }
        }
        return (out.length == 1 ? out[0] : (out.length > 1 ? out : null));
    };
}

暫無
暫無

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

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