2013-07-29 22 views
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/

回答

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

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 
}); 
1

老實說,我只是把所有的將按鈕放入html中並隱藏並顯示它們,而不是將它們注入到文檔中。