Как перезагрузить указанный элемент c DIV с помощью нажатия кнопки? - PullRequest
0 голосов
/ 10 января 2020

В моем коде HTML есть 3 компонента. 2 тега DIV и 1 кнопка. Я хочу, чтобы первый тег DIV перезагрузился при нажатии кнопки. Я применил jQuery, но по нажатию кнопки ничего не происходит. Вот мой код HTML, встроенный вместе с кодом JS.

<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <!--Font Awesome Icons-->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
    <title>DIV Load Testing</title>

</head>

<body>

    <button id="reloader" type="button" class="btn btn-primary btn-sm">
        <i class="fas fa-chevron-circle-left"></i> Reload
    </button>
    <!--DIV TAG TO BE RELOADED ON THE BUTTON CLICK-->
    <div class="container" id="content">
        <h1>Reloads</h1>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

        <img src="colorizer-desktop.PNG">

        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    </div>
<!---->

    <div class="container">
        <h1>Test</h1>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
        <img src="image-desktop.PNG">
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            $('#reloader').click(function(){
               // alert('ok');
                $('#content').load(' #content');
            });
        });

        //function myButton() {
        //    location.reload();
        // }
    </script>
</body>

</html>

Я использовал 2 сценария ios:

  1. С помощью jQuery.
  2. С помощью функции location.reload();.

Функция location.reload() перезагружает всю страницу, но я хочу, чтобы только первый тег DIV был перезагружен щелчок кнопки.

Пожалуйста, помогите в этой функции!

Ответы [ 2 ]

0 голосов
/ 10 января 2020

С jQuery .load () :

Метод .load(), в отличие от $.get(), позволяет нам указать часть удаленного документа, которая будет вставлено. Это достигается с помощью специального синтаксиса для параметра url. Если в строку включен один или несколько пробельных символов, предполагается, что часть строки, следующая за первым пробелом, является селектором jQuery, определяющим загружаемый контент.

Мы могли бы изменить приведенный выше пример использовать только часть извлеченного документа:

$( "#result" ).load( "ajax/test.html #container" );

Когда этот метод выполняется, он извлекает содержимое ajax/test.html, но затем jQuery анализирует возвращенный документ в найти элемент с идентификатором контейнера. Этот элемент вместе с его содержимым вставляется в элемент с идентификатором результата, а остальная часть извлеченного документа отбрасывается.

jQuery использует свойство браузера .innerHTML для анализа полученного документа. и вставьте его в текущий документ. Во время этого процесса браузеры часто фильтруют элементы из документа, такие как <html>, <title> или <head>. В результате элементы, полученные с помощью .load(), могут не совпадать с данными, полученными непосредственно браузером.

Таким образом, ваш сценарий должен выглядеть следующим образом:

$(function() {
  $('#reloader').click(function() {
    var self = window.location.href;
    console.log("Loading '#content' from " + self);
    $('#content').load(self + ' #content');
  });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="reloader" type="button" class="btn btn-primary btn-sm"><i class="fas fa-chevron-circle-left"></i> Reload</button>
<div class="container" id="content">
  <h1>Reloads</h1>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

  <img src="colorizer-desktop.PNG">

  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

Примечание: Этот фрагмент не будет работать в этой среде и должен быть протестирован в вашем собственном коде.

0 голосов
/ 10 января 2020

Понятия не имею, что вы подразумеваете под «перезагрузить div». Что вы ожидаете?

Кроме того, функция jQuery .load () используется для загрузки удаленного файла с сервера и отображения его содержимого. Вам нужно сообщить функции, какой файл ей нужно загрузить:

$('#content').load('sample.html');

Итак, если ваш html файл с функцией Javascript имеет имя index. html, ваш вызов будет:

$('#content').load('index.html #content');

Это скажет вашей функции, что она должна загрузить div #content из индекса файла. html.

...