我的代码
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function process(e) {
alert("Hello! I am an alert box1!!");
e.hide();
};
$(document).ready(function() {
var p = $("#id1"); //jquery object
p.click(function() {
process(this); //line A
});
});
</script>
</head>
<body>
<p id=id1>If you click on me, I will disappear.</p>
</body>
</html>
点击文字不消失,控制台报错:
TypeError: e.hide is not a function
但是如果我将 A 行代码更改为如下
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function process(e) {
alert("Hello! I am an alert box1!!");
e.hide();
};
$(document).ready(function() {
var p = $("#id1"); //jquery object
p.click(function() {
process(p); //change this to p, Line A
});
});
</script>
</head>
<body>
<p id=id1>If you click on me, I will disappear.</p>
</body>
</html>
它有效!!!
我也尝试了代码:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function process(e) {
alert("Hello! I am an alert box1!!");
e.style.visibility = "hidden";
};
$(document).ready(function() {
var p = $("#id1")[0]; //jquery object to dom object
p.addEventListener("click", function() {
process(this);
});
});
</script>
</head>
<body>
<p id=id1>If you click on me, I will disappear.</p>
</body>
</html>
它也有效。
欢迎评论
最佳答案
您可以使用console.log()
查看javascript如何处理您发送的内容.
正在做console.log(this)
在日志中给出这个:
<p id="id1">If you click on me, I will disappear.</p>
您可以看到的是普通的 DOM 对象。
但是,做console.log(p)
在日志中给出这个:
[p#id1, context: document, selector: "#id1"]
它代表一个可以操作的 jQuery 对象。如果您希望 jQuery 为您从 this
中提取对象,将您发送的内容包装在 jQuery 中:
function process(e){
alert("Hello! I am an alert box1!!");
$(e).hide(); // Wrap to convert DOM object.
};
$(document).ready(function(){
var p =$("#id1");//jquery object
p.click(function(){
process(this);//change this to p, Line A
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id=id1>If you click on me, I will disappear.</p>
关于javascript - 将对象传递给函数但无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31412389/