我有一个功能,只需点击一下,就会创建2个按钮。
$(document).ready(function() {
$('#Refresh').on('click', basket());
function basket(){
var duplicate = document.createElement('button');
// Write the text for button
var duplicate_text = document.createTextNode("Duplicate");
duplicate.appendChild(duplicate_text);
$(document.body).append(duplicate);
// Create display button
var display = document.createElement('button');
// Write the text for button
var display_text = document.createTextNode("Display");
display.appendChild(display_text);
$(document.body).append(display);
}
});
如果整个篮子函数在.on函数内部,它都有效。但是,当我像上面那样把它拿出来时,它就停止了工作。
这是什么问题?这是关于我缺乏回报吗?
答案 0 :(得分:0)
You could return the function as shown below
$(document).ready(function() {
$('#Refresh').on('click', basket);
function basket(){
var duplicate = document.createElement('button');
// Write the text for button
var duplicate_text = document.createTextNode("Duplicate");
duplicate.appendChild(duplicate_text);
$(document.body).append(duplicate);
// Create display button
var display = document.createElement('button');
// Write the text for button
var display_text = document.createTextNode("Display");
display.appendChild(display_text);
$(document.body).append(display);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="Refresh" value="Refresh"/>
答案 1 :(得分:0)
You are calling basket()
prematurely, in the click
method. Don't call basket
:
$('#Refresh').on('click', basket);
// Note basket has no parens, because we are not calling it.