最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reload particular element with jQuery - Stack Overflow

programmeradmin2浏览0评论

I'm trying to reload particular element on button on click using jQuery, but when I click the button, the entire page gets loaded in this element. I have tried the following code which loads the entire page in this element. I want to load only particular element.

$(document).ready(function() {
    $("#button").click(function() {
        $("#demo").load(location.href + "#demo");
    });
});
<div id="example">
    <p id="demo">hi</p>
    <button id="button" type="button">press</button>
</div>

I'm trying to reload particular element on button on click using jQuery, but when I click the button, the entire page gets loaded in this element. I have tried the following code which loads the entire page in this element. I want to load only particular element.

$(document).ready(function() {
    $("#button").click(function() {
        $("#demo").load(location.href + "#demo");
    });
});
<div id="example">
    <p id="demo">hi</p>
    <button id="button" type="button">press</button>
</div>
Share Improve this question edited Oct 7, 2022 at 17:37 KyleMit 29.9k72 gold badges506 silver badges697 bronze badges asked Apr 13, 2016 at 6:53 Arun KumareshArun Kumaresh 6,3116 gold badges35 silver badges50 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 18

You can use load() with selector.

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

This will load only the #demo element from the location.href URL.

You have to load the page using $.get() and extract the #demo fragment:

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

You can use Ajax, then create element with responseText, then put it into the div:

<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>

But You load the entire page, it might me not usefull. I suggest to make a php script which just returns the requested data, and call it via Ajax at page load and at button click...

发布评论

评论列表(0)

  1. 暂无评论