2016-09-13 31 views
1
<div class="box"> 
<span class="test"></span> 
</div> 
<div class="row"></div> 
<input type="button" value="Add" id="button"> 

<style type="text/css"> 
    .box { 
     display: none; 
    } 
</style> 

上述股利是不可見的,當頁面加載。點擊按鈕後,我們可以看到div。現在我想追加文本跨度當div是可見的。jQuery的文本添加到跨過當DIV可見

$('#button').on("click",function(e){ 
    e.preventDefault(); 
    $('.box').clone().show().append('.row'); 
}); 

我想這

1) $(".box").closest(".test").text("hello"); 
2) $(".box").find(".test").text("hello"); 

但它不添加文本跨度。

+1

嘗試'$( 「箱子 」)查找文本( 「你好」)。(「 測試」);' –

+0

@KartikeyaKhosla使用find不工作。 – rajesh

+1

使用'.clone()'的目的是什麼? – Satpal

回答

0

.closest橫穿父元素。您需要使用.find(),而不是.closest()選擇要搜索的子元素:

$(".box .test").text("hello"); 

$(".box").find(".test").text("hello"); 

Working Demo

0

您neeed使用find()與選擇visible而不是closest()

closest()尋找與選擇的家長給定類的元素,同時發現着眼於選擇

$(".box:visible").find(".test").text("hello"); 

的兒童,這是因爲你找的語句被執行前它不加入您的div是可見的。你需要在你執行你添加文字聲明的div已經可見,如圖所示摘錄如下

$(function(){ 
 
     $('#toggle').click(function(){ 
 
     console.log('click'); 
 
     $('.box').css("display", "block"); 
 
     $('.box').find('.test').text("Hello"); 
 
     }) 
 
     
 
    
 
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <div class="box"> 
 
    
 
    <span class="test"></span> 
 
    
 
    </div> 
 
    <button id="toggle">toggle</button>

+0

不能使用find()。 – rajesh

0

它會工作試試這個:

$(document).ready(function(){ 

    $("button").on("click",function(){ 

     $(".box").find(".test").text("hello"); 

     $(".box").show(500); 

    }) 

}) 

最終代碼:

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    
 
    <style type="text/css"> 
 
     .box { 
 
      display: none; 
 
     } 
 
    </style> 
 
    
 
</head> 
 
    <body> 
 
     
 
     <div class="box"> 
 
      <span class="test"></span> 
 
     </div> 
 
     <div class="row"></div> 
 
     
 
     <button>SHOW DIV</button> 
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
     <script> 
 
      
 
     $(document).ready(function(){ 
 

 
      $("button").on("click",function(){ 
 

 
       $(".box").find(".test").text("hello"); 
 

 
       $(".box").show(500); 
 

 
      }) 
 

 
     }) 
 
    
 
     </script> 
 
    </body> 
 
</html>

0

您需要使用.find()/.children()/Descendant Selector (「ancestor descendant」)來定位test元素。

此外,你需要使用.appendTo()代替.append()

.append().appendTo()方法執行相同的任務。主要的區別是在語法,具體而言,在內容和目標的位置。

jQuery(function($) { 
 
    $(".box:first") 
 
    .clone() 
 
    .find(".test") 
 
    .text("hello") 
 
    .end() 
 
    .show() 
 
    .appendTo('.row'); 
 
});
.box { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div class="box"> 
 
    <span class="test"></span> 
 
</div> 
 
<div class="row"></div>