我使用onclick事件设置了两个文本框值。我曾两次使用javascript:
,我认为这可以用更短的方式编写。如何以简短或更好的方式编写onclick?
<button type="button" onclick="javascript:document.getElementById('category').value='Furniture'; javascript:document.getElementById('tick').value='';">Furniture Option</button>
OR
<button type="button" onclick="shortened();">Furniture Option</button>
function shortened(){
javascript:document.getElementById('category').value='Furniture';
javascript:document.getElementById('tick').value='';
}
答案 0 :(得分:1)
将Javascript与HTML分开:
<button type="button" id="furniture-button">Furniture Option</button>
<script>
function shortened() {
document.getElementById('category').value='Furniture';
document.getElementById('tick').value='';
}
var furniture_button = document.getElementById("furniture-button");
furniture_button.addEventListener("click", shortened);
// or, the deprecated way:
// furniture_button.onClick = shortened;
</script>
答案 1 :(得分:0)
为按钮提供ID并使用JavaScript附加侦听器。不要在HTML中添加JavaScript代码:)
var button = document.getElementById('button');
button.addEventListener('click', function () {
// Business Logic
alert('Clicked');
}, false);
<button id="button">Button</button>