当我控制日志“this”时,它显示正确的容器和正确的HTML树。当我尝试this.method()时,它说在这种情况下不能引用它。
我的目标是能够定位“this”的孩子,其中“this”是div容器。我遇到的问题是浏览器拒绝识别它有子节点,即使它可以在没有.children或者附加到它的任何jquery方法(this.val()或this.parent)时引用它。 (),等等。)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script type = "text/javascript">
$(document).ready(function(id) {
var contactCardNo = 0;
var newVar = "";
$(document).on('click', ".contact", function() {
alert(this);
console.log(this);
console.log($(this.children()));
/*if ($(newVar ).is(":hidden")) {
$(".contactDescription").hide();
$(newVar).show();
} else {
$(".contactDescription").show();
$(newVar).hide();
}*/
});
function attach_handler() {
//$(newVar).click(function() {
// alert(this);
//});
//alert(newVar);
var newVar = "\"" + newVar + "\"";
alert(newVar);
};
$(document).on('click', '#submitButton', function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var description = $("#description").val();
var idToAttach = "#contact" + contactCardNo++;
$("#contacts").append("<div class = 'contact'><p>" + firstName + " " + lastName + "</p><p class = 'contactDescription'>Click for a description!</p><p class = 'description'>" + description + "</p></div>");
$(idToAttach).css('width', '300px');
$(idToAttach).css('height', '150px');
$(idToAttach).css('display', 'block');
newVar = idToAttach;
attach_handler();
$(idToAttach).hide();
return false;
});
});
</script>
<style type = "text/css">
*{
padding:0px;
margin:0px;
}
#container{
width:800px;
height:800px;
display:inline-block;
}
#contactForm {
width:400px;
height:400px;
display:inline-block;
vertical-align:top;
}
#contacts {
width:390px;
height:800px;
display:inline-block;
}
.contact {
width:300px;
height:150px;
display:block;
}
.description {
width: 280px;
height: 100px;
}
div{
border:1px solid #000;
}
</style>
</head>
<body>
<div id = "container">
<span>
<div id = "contactForm">
<form>
<p>First Name: <input type = "text" name = "firstName" id = "firstName" /></p>
<p>Last Name: <input type = "text" name = "lastName" id = "lastName" /></p>
<p>Description:</p>
<p><input type = "textarea" id = "description" /></p>
<p><input type = "button" value = "Add Contact" id = "submitButton" /></p>
</div>
<div id = "contacts">
</div>
</span>
</div>
</body>
</html>
答案 0 :(得分:2)
jQuery使用$(this)
代替this
。
答案 1 :(得分:1)
有时括号可能很棘手。在运行this
方法之前,您需要将children()
传递给jQuery。
改变这个:
console.log($(this.children()));
对此:
console.log($(this).children());