2017-02-20 53 views
0

如何爲沒有任何ID或類的輸入標籤添加ID?是否有可能是這樣的:如何使用JavaScript爲輸入標籤添加ID?

<div id="1">hey all</div> 
<input type="text" name="txt" /> 

<script> 
    document.querySelector('input[type="search"]').id = 'sinput'; 
    document.getElementById("sinput").addEventListener("keypress", function() { 
     document.getElementById("1").style.display ="none"; 
    }); 
</script> 
+1

輸入'' – nogad

+3

好吧,一開始......您的輸入類型是「text」,但在您嘗試獲取的選擇器中'搜索'... – NewToJS

回答

0

嘗試以下操作:

var elem = document.getElementsByTagName('input'); 
 
elem[0].setAttribute("id", "txtName"); // important to use proper index here in case there are multiple input elements in the document. 
 
console.log(document.getElementsByTagName('input')[0])
<input type="text" name="txt" />

0

好吧,我還沒有看到一個答案,告訴你當前的源代碼和它的問題沒有出現你已經承認我的評論,所以也許你會顯示你的工作片段將做。

您需要更改的唯一的事情就是type屬性從textsearch您選擇'input[type="search"]'匹配,或者改變您的選擇相匹配的輸入型'input[type="text"]'

更改輸入type = 搜索

document.querySelector('input[type="search"]').id = 'sinput'; 
 
document.getElementById("sinput").addEventListener("keypress", function() { 
 
     document.getElementById("1").style.display ="none"; 
 
});
<div id="1">hey all</div> 
 
<input type="search" name="txt" />


或改變選擇input[type="特牛逼"]

document.querySelector('input[type="text"]').id = 'sinput'; 
 
document.getElementById("sinput").addEventListener("keypress", function() { 
 
     document.getElementById("1").style.display ="none"; 
 
});
<div id="1">hey all</div> 
 
<input type="text" name="txt" />

如果您有任何疑問,請隨時在下面評論,我會盡快回復您。

我希望這會有所幫助。快樂的編碼!

+0

非常感謝。 它在新項目 與我的工作,但沒有爲這個項目 「我要顯示所有表當我按下輸入輸入」 這個我的網站項目 http://sci.mu.edu.iq/?page_id= 3347 請幫助我 –

+0

此爲代碼

相關問題