这样的事情: 当我点击“添加”内容更改内容时,当我点击“完全”时内容会回来。代码就在这里。链接:
[代码] [1] 当我点击“添加”时,如何再次单击“完全”?
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#department a {
text-decoration: none;
}
#department span {
display: inline-block;
color: red;
margin-right: 20px;
}
#department p {
display: inline;
}
#department p span {
color: green;
font-weight: bold;
}
#department input {
width: 100px;
margin-right: 20px;
}
</style>
<script src="../jquery-1.10.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#department >p a").click(function() {
$("#department p").empty()
$("#department p").append('<input type="text" name="department"><a href="javascript:void(0)">quite</a>')
})
})
</script>
</head>
<body>
<div id="department">
<span>department</span>
<p>
<span>office</span>
<span>seek</span>
<a href="javascirpt:void(0);">add</a>
</p>
</div>
</body>
</html>
我把代码放在这里:http://jsfiddle.net/Jackyhua/zTkXL/
答案 0 :(得分:1)
老实说,我只是将所有按钮放入html并隐藏并显示它们,而不是将它们注入文档中。
答案 1 :(得分:0)
这些方面的东西。
$(document).ready(function () {
// These variables hold the HTML that has to be shown when the
// structure changes
var $quite = '<input type="text" name="department">'
+ '<a class="quite" href="javascript:void(0)">quite</a>';
var $add = '<span>office</span> <span>seek</span>'
+ '<a class="add" href="javascirpt:void(0);">add</a>';
// Use event Delegation
// You are dynamically adding and removing elements.
// So normal binding of event will not work
$('#department').on('click', '.quite, .add', function(e) {
var $department = $("#department p");
$department.empty();
// Added specific classes to anchors to target them
$(e.target).hasClass('quite') ? $department.append($add) : $department.append($quite);
});
})
<强> Check Fiddle 强>
答案 2 :(得分:0)
创建元素时,您需要使用动态事件处理程序(而不仅仅是.click()
):请参阅.on()
的文档:here。那里也有很多很好的例子。在您的情况下,您可以添加一个类名来触发事件处理程序:如下所示:
HTML:
<div id="department">
<span>department</span>
<p>
<span>office</span>
<span>seek</span>
<a class="add">add</a>
</p>
</div>
JQuery的:
$("#department .add").on('click', function (e) {
//this replaces the need for javascript:void
e.preventDefault();
//you can chain functions, since you're operating on the same element
$(this).parent('p')
.empty()
.append('<input type="text" name="department"><a class="quite">quite</a>')
});
$("#department .quite").on('click', function (e) {
//this replaces the need for javascript:void
e.preventDefault();
//do something else
});