$(document).ready(function () {
function somefunction(input) {
$('div').html(input);
}
$("#assign").click(function () {
//assign the value only
somefunction("from assign to putput")
});
$("#output").click(function () {
//run the function
somefunction();
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="assign" value="assign" />
<input type="button" id="output" value="output" />
<div></div>
如何在一个按钮中为函数赋值,并在另一个按钮上运行该函数?
任何建议都会被接受。
发布于 2015-11-26 16:36:47
只需将值赋给函数作用域之外的变量即可。
$(document).ready(function () {
var assignedvalue = "";
function somefunction() {
$('div').html(assignedvalue);
}
$("#assign").click(function () {
//assign the value only
assignedvalue = "from assign to putput";
});
$("#output").click(function () {
//run the function
somefunction();
});
});发布于 2015-11-26 16:36:38
为什么不使用全局变量而不是在函数中赋值?
$(document).ready(function () {
var input = "";
function somefunction() {
$('div').html(input);
}
$("#assign").click(function () {
//assign the value only
input = "from assign to putput";
});
$("#output").click(function () {
//run the function
somefunction();
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="assign" value="assign" />
<input type="button" id="output" value="output" />
<div></div>
如果你不想使用全局变量,你可以先给div属性赋值,如下所示:
$(document).ready(function () {
function somefunction() {
$('div').html($('div').attr('temp-value'));
}
$("#assign").click(function () {
//assign the value only
$('div').attr("temp-value","from assign to putput");
});
$("#output").click(function () {
//run the function
somefunction();
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="assign" value="assign" />
<input type="button" id="output" value="output" />
<div></div>
发布于 2015-11-26 16:44:22
$(document).ready(function () {
var input="";//Global Variable initially assigned as empty
function somefunction(input) {
$('div').html(input);
}
$("#assign").click(function () {
//assign the value only
input="Some Value";//Assigning the global variable
});
$("#output").click(function () {
//run the function
somefunction(input);
input="";//Clear the global variable after the success of 'somefunction'
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="button" id="assign" value="assign" />
<input type="button" id="output" value="output" />
<div></div>
https://stackoverflow.com/questions/33933817
复制相似问题