是否可以使用javascript/jQuery在页面加载(或(document).ready)上创建对象,然后在以后使用它们,例如在输入的keyup上。如果是,如何?
如果将所有代码都放在$(document).ready{all code here}
中,则变量不会超出范围。
$(document).ready(function(){
var someObject={};
$("selector").click(function(e){
console.log(someObject);
});
});
如果你在html中使用onclick,那么我建议你改变这一点,并将所有JS代码移动到JS文件或<script>
块(不在你的html中)。
不需要将许多变量放在全局作用域上,您可以为其命名(如果不能将所有代码放在$(document).ready中)
var myApplication = myApplication || {};//if myApplication doesn't exist then create it
myApplication.someObject = {};
然后,即使JS分布在多个文件中,您仍然可以维护一个myApplication对象。
如gp所述;可以使用数据将数据添加到html元素:
$("#somebutton").on("click",function(e){
$(this).data("someObject",{});// you can use e.target instead of this as well
});
下面是一个用法示例。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
TODO write content
<div id="MytextID">My text </div>
<input type="text" id="inputId" name="name">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = $('#MytextID');
$('#inputId').keyup(function(){
alert(x.text());
})
})
</script>
</body>
</html>