2

像这样的事情:当我点击“添加”内容改变内容,当我点击“相当”内容回来。代码在这里。链接:

[code][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/

4

3 回答 3

1

老实说,我只是将所有按钮放入 html 中并隐藏和显示它们,而不是将它们注入到文档中。

于 2013-07-29T04:12:48.710 回答
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);
    });
}) 

检查小提琴

于 2013-07-29T03:45:52.287 回答
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>

查询:

$("#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
});
于 2013-07-29T03:46:07.833 回答