【发布时间】:2015-01-24 19:13:18
【问题描述】:
任何人都可以解释回调中的this。
示例。 网页。
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="myApp.js"></script>
</head>
<body>
<button type="button" id="btn001">Show</button><br/>
<p id="p001" class="article">Some contents...</p>
<button type="button" id="btn002">Show</button><br/>
<p id="p002" class="article">Other content...</p>
<!-- more paragraphs -->
</body>
</html>
首先,我为每个段落编写了一个函数。 myApp.js的源代码。
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
$("#p001").toggle();
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
$("#p002").toggle();
});
// repeat code for next paragraphs
});
我对代码重复很生气,所以我尝试排除代码来运行。
function handleHideShow(par) {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
par.toggle();
}
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
handleHideShow($("#p001"));
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
handleHideShow($("#p002"));
});
});
切换段落有效,但button 上的文本没有改变。谁能解释this 发生了什么?
- 为什么在第一个示例中
$(this)选择了被点击的元素? - 第二个示例中的
$(this)是什么?
以及如何解决这个问题?
【问题讨论】:
标签: javascript jquery button click