[英]Return the value of a JS function and use it as the value for an input button
我想設置一個返回字符串的JavaScript函數,該字符串用作按鈕的值。 像這樣的東西:
function test(){
x = "some text";
return x;
}
我想在value屬性的input元素中使用此函數。 像這樣的東西:
<input type="button" id="s1" value="test()" />
不幸的是,按鈕不會在按鈕上顯示“某些文本”,而是“test()”。 我怎樣才能解決這個問題?
你可以這樣做:
<input type="button" id="s1" value="" />
<script type="text/javascript">
var elem = document.getElementById("s1");
elem.value = "some text";
</script>
您還可以使用自定義數據屬性以優雅的方式執行此操作。
在這里查看JSFiddle演示: http : //jsfiddle.net/NJ5sK/
基本上,您使用應調用的函數名稱標記輸入元素以返回其值。 然后,您獲取具有data-value-function
屬性的所有元素,運行該函數並分配該值。
HTML:
<input type="text" data-value-function="cheese" />
<input type="text" data-value-function="animal" />
JS:
window.cheese = function() {
return "Limburger";
}
window.animal = function() {
return "Cat";
}
var elements = document.querySelectorAll('*[data-value-function]');
for (var i = 0; i < elements.length; i++) {
var valueFunctionName = elements[i].getAttribute('data-value-function');
elements[i].value = window[valueFunctionName]();
}
請享用!
html按鈕的value屬性僅接受文本。 看到這里 。
我從你的問題中理解的是你想要一個html按鈕,其值應該由javascript函數設置。 你可以通過其他方式實現這一目標。
使用document.getElementById
獲取button元素並在test()
設置value
你的代碼應該是這樣的:
<input type="button" id="s1"/>
<script>
function test(){
document.getElementById('s1').value ='some text'; //s1 is the id of html button
};
test(); //dont forget to call function
</script>
function test(){
x = "some text";
document.getElementById('s1').value = x;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.