2014-06-10 14 views
0

我用我的PHP代碼使用10 <div>class='ThisOne' -如何在動態創建的id選擇器上顯示ajax結果?

<?php  
for ($i=0;$i<=10;$i++) { 
?> 
<div id=""> 
    <input type="text" id="GetCommentText-<?php echo $i;?>"></input> 
    <input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>"></input> 
    <button type="button" id="SelectPostComment-<?php echo $i;?>" data-target="<?php echo $i;?>" >Submit</button> 
</div> 
<div id="ShowAjaxesult-<?php echo $i;?>" class="Thisone" style="" ></div> 
<?php 
} 
?> 

我想擴大<div>id="ShowAjaxesult-5"<button>id="SelectPostComment-5"用戶點擊。當用戶點擊<button>id="SelectPostComment-8"等時,同樣擴展<div>id="ShowAjaxesult-8"

對於這個JS,我使用的模樣 -

  <script type="text/javascript" language="javascript"> 
      $(document).ready(function() { 
       $("[id^=SelectPostComment-]").click(function(){ 
        var $Parent = $(this).parent(); 
        var CommentText = $Parent.find('[id^="GetCommentText-"]:first').val(); 
        var PostID = $Parent.find('[id^="GetPostID-"]:first').val(); 

        $.ajax({ 
         type : 'GET', 
         url:'test1.php', 
         data : {CommentText: CommentText, PostID: PostID}, 
         success:function(data) {        
         $("[id^=ShowAjaxesult-]").html(data); 
         } 
        }); 
       }); 
      }); 
      </script> 

問題與上面的代碼是,當我在任何<button>點擊顯示所有<div>(所有<div>ShowAjaxesult-1ShowAjaxesult-2和... 。ShowAjaxesult-10)。我想每<button>點擊一個<div>,這取決於它的id選擇器的值。如選擇<div id='ShowAjaxesult-2'>選擇<button id='SelectPostComment-2'>等。不知道我在做什麼錯誤。請幫忙。

+0

是'CommentText'和'PostID'正確的和預期值? – Pankrates

+0

@Pankrates是的。我得到正確的CommentText和PostID – vvk

回答

1

添加類的按鈕和輸入,你可以這樣做:

<script> 
    $(document).ready(function() { 
     $(".subBtn").click(function(){ 
      var $Parent = $(this).parent(); 
      var CommentText = $Parent.find('.getComment').val(); 
      var PostID = $Parent.find('.getPost').val(); 

      $.ajax({ 
       type : 'GET', 
       url:'test1.php', 
       data : {CommentText: CommentText, PostID: PostID}, 
       success:function(data) {        
       $Parent.next().html(data); 
       } 
      }); 
     }); 
    }); 
    </script> 
+0

它爲我工作。謝謝。 – vvk

3

更改

    $("[id^=ShowAjaxesult-]").html(data); 

分爲:

    $("#ShowAjaxesult-"+PostID).html(data); 

製造它爲我工作。

+0

的值謝謝。它也適用於我。但是使用類選擇器會更好,因爲@realseanp在他的回答中提出了建議。 – vvk

0

我不熟悉的ID^=語法,但你的選擇是不夠具體。你可以從你的按鈕的id是這樣的指標:

var i = $(this).split('-')[1]; 

然後將其附加到你的Ajax結果DIV這樣的:

$("[id=ShowAjaxesult-"+i+"]").html(data); 

在我發現使用「$父」作爲一個側面說明變量名稱令人不安。你只是簡單地在這裏混合使用PHP語法,還是有一些意義,在前面添加一個美元符號並使第一個字母大寫?

乾杯,

傑西