Javascript 使用 jQuery 重新加载特定元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36590722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:15:34  来源:igfitidea点击:

Reload particular element with jQuery

javascriptjqueryajax

提问by Arun Kumaresh

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.

我正在尝试使用 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>

回答by Tushar

You can use load()with selector.

您可以load()与选择器一起使用。

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

This will load only the #demoelement from the location.hrefURL.

这将仅加载#demo来自location.hrefURL的元素。

回答by Micha? Per?akowski

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

您必须使用加载页面$.get()并提取#demo片段:

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

回答by Vincent

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

你可以使用Ajax,然后用responseText创建元素,然后放入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...

但是你加载了整个页面,它可能对我没有用。我建议制作一个 php 脚本,它只返回请求的数据,并在页面加载和按钮单击时通过 Ajax 调用它...