2016-05-03 83 views
2

我想弄清楚如何在不刷新瀏覽器的情況下同時點擊我的按鈕。我注意到,如果我點擊其中一個按鈕的工作,並使用.replaceWith替換它的新值,但是當我點擊另一個按鈕時,它不會給我另一個值。使用replaceWith同時單擊按鈕而不刷新瀏覽器

代碼:

<body> 
<input type = "button" id = "bt1" value = "See my Full Name :)"> 
<input type = "button" id = "bt2" value = "See my Nickname :)"> 

<div> 
    <div class = "name">See my name</div> 
</div> 

<script> 

    $(document).ready(function() 
    { 
     $("#bt1").click 
     (
      function() 
      { 
       $("div.name").replaceWith("<div>John Francis</div>"); 
       alert("Your full name is John Francis"); 
      } 
     ); 

     $("#bt2").click 
     (
      function() 
      { 
       $("div.name").replaceWith("<div>Francis</div>"); 
       alert("Your nickname is Francis"); 
      } 
     ); 
    }); 

</script> 

回答

2

你不加入的類名.name給您更換新插入的DIV,所以,下一次你點擊,有帶班沒有元素.name

這將是一個更容易剛剛更新文本

$(document).ready(function() { 
    $("#bt1").click(function() { 
     $(".name").text("John Francis"); 
     alert("Your full name is John Francis"); 
    }); 

    $("#bt2").click(function() { 
     $(".name").text("Francis"); 
     alert("Your nickname is Francis"); 
    }); 
}); 

FIDDLE

如果由於某種原因,你必須使用replaceWith (你沒有),只需添加類

$(document).ready(function() { 
    $("#bt1").click(function() { 
     $(".name").replaceWith("<div class='name'>John Francis</div>"); 
     alert("Your full name is John Francis"); 
    }); 

    $("#bt2").click(function() { 
     $(".name").replaceWith("<div class='name'>Francis</div>"); 
     alert("Your nickname is Francis"); 
    }); 
}); 

FIDDLE

+0

爲什麼我應該使用'.text'而不是'.replaceWith'有沒有使用'.replaceWith'的方法? – Francisunoxx

+0

我會投票給你的第二個小提琴。大。 – Atula

0
$(document).ready(function() 
{ 
    $("#bt1").click 
    (
     function() 
     { 
      $('div.name').text("") 
      $("<div>John Francis</div>").appendTo('div.name'); 
      alert("Your full name is John Francis"); 
     } 
    ); 

    $("#bt2").click 
    (
     function() 
     { 
      $("div.name div").replaceWith("<div>Francis</div>"); 
      alert("Your nickname is Francis"); 
     } 
    ); 
}); 
相關問題