2016-04-13 34 views
1

jQueryを使用してボタン上の特定の要素をリロードしようとしていますが、ボタンをクリックするとこの要素にページが読み込まれます。この要素のページ全体をロードする次のコードを試しました。私は特定の要素だけをロードしたい。特定の要素をjQueryでリロードする

<script> 
    $(document).ready(function() { 
     $("#button").click(function() { 
      $("#demo").load(location.href + "#demo"); 
     }); 
    }); 
</script> 
</head> 

<body> 
    <div id="example"> 
     <p id="demo">hi</p> 
     <button id="button" type="button">press</button> 
    </div> 

答えて

6

あなたはセレクタでload()を使用することができます。

$("#demo").load(location.href + " #demo"); // Add space between URL and selector. 
           ^

これはlocation.href URLからのみ#demo要素をロードします。

2

あなたは$.get()を使用してページをロードし、#demoの断片を抽出する必要があります。

$("#button").click(function() { 
    $.get(location.href).then(function(page) { 
    $("#demo").html($(page).find("#demo").html()) 
    }) 
}) 
1

あなたは、その後のdivに入れて、その後、responseTextを持つ要素を作成し、アヤックスを使用することができます。

<head> 
    <script> 
     $(document).ready(function() { 
      $("#button").click(function(){ 
       $.ajax({ 
        url: location.href, 
        type: 'GET', 
        sucess: function(data) 
        { 
         refreshedPage = $(data); 
         newDemo = refreshedPage.find("#demo").html(); 
         $('#demo').html(newDemo) 
        } 
       }); 
      } 
     } 
    </script> 
</head> 

<body> 
    <div id="example"> 
     <p id="demo">hi</p> 
     <button id="button" type="button">press</button> 
    </div> 
</body> 

しかし、あなたはページ全体を読み込み、それは私には便利ではないかもしれません。私は、要求されたデータを返すだけのPHPスクリプトを作成し、ページロード時とボタンクリック時にAjax経由で呼び出すことをお勧めします。

関連する問題