我正在尝试执行以下操作: 2个div,可点击返回div的“值”。这是通过在div上创建(内部)get_value函数来实现的。
但我真的想要的是有一个按钮,它通过调用get_value函数读取div的值。 例如,见下面的代码。
不幸的是我无法让它发挥作用......
我试图使值全局化,但随后它们被覆盖......
任何线索?
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Js/jquery-1.10.2.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
initdiv("a", 10)
});
$(document).ready(function () {
initdiv("b", 20)
});
function initdiv(id, value) {
function get_value() {
return value;
};
$("#" + id).click(function () {
alert(get_value());
});
}
function getFoo() {
var obj = $("#a");
alert(obj.get_value());
}
</script>
</head>
<body>
<form id="form2" runat="server">
<div id="a">
foo
</div>
<div id="b">
bar
</div>
<input type="button" onclick="getFoo();" value="click me and get the value of DIV 'foo'" />
</form>
</body>
</html>
答案 0 :(得分:0)
每次执行init_div
函数时写入函数都是不必要的。此功能也适用于您:
$('div').click(function() {
alert($(this).text()); //or '.html()'
});
对于按钮,您可以使用相同的方法:
$('button').click(function() {
alert($('div#a').text()); //or '.html()'
});
如果你想使它更通用,你可以使用它:
<强>的jQuery 强>
function get_value(selector) {
alert($(selector).text());
}
$(document).ready(function () {
$('div').click(function () {
get_value(this);
});
});
<强> HTML 强>
<input type="button" onclick="get_value('.foo')" value="click me and get the value of DIV 'foo'" />