2014-12-07 77 views
0

我有這一點代碼來自動選擇輸入字段中的文本。將函數應用於所有文本輸入字段

onclick="this.focus();this.select()" 

和我,像這樣

<input type="text" onclick="this.focus();this.select()" value="xxxxx"> 

我想這將是更清潔和更容易地進行更新,如果我是在全球範圍內,而不是應用內嵌的這段代碼執行它。

我該如何去從一個外部.js文件添加此代碼到所有文本輸入標籤(或可能到具有特定ID的文本輸入標籤)?

回答

0

作爲<input />元素會自動集中在點擊該元素,你應該只需要this.select()

$('input[type="text"]').on('click', function() { 
 
    this.select(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" value="something" /> 
 
<input type="text" value="something else" /> 
 
<input type="text" value="something other" />

而且,如果你想避免的jQuery這一點,你可以簡單地說:

function selectThis() { 
 
    return this.select(); 
 
} 
 

 
Array.prototype.forEach.call(document.querySelectorAll('input[type=text]'), function (input) { 
 
    input.addEventListener('click', selectThis); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" value="something" /> 
 
<input type="text" value="something else" /> 
 
<input type="text" value="something other" />

參考文獻:

+0

我走了jQuery選項的一致性項目。謝謝。 – pedalGeoff 2014-12-07 22:07:37

+0

你真的很受歡迎,我很高興有幫助:) – 2014-12-07 23:05:44

1

你可以通過這個代碼使這個全球性的tyoe的所有文字輸入

$("input[type=text]").click(function(){ 

$(this).focus(); 
$(this).select(); 
///do something here 
}): 
0

試試這個:

$(document).on('click', 'input:text', function() { 
    $(this).select(); 
}); 
相關問題