【问题标题】:How to show and hide partial view on button click?如何在按钮单击时显示和隐藏部分视图?
【发布时间】:2019-08-07 22:25:36
【问题描述】:

我想在单击同一个按钮时显示和隐藏我的局部视图。 下面的代码用于显示部分视图。如果用户再次单击同一个按钮,如何删除部分视图?

<div id="myPartialView"></div>
$('#myBtn').click(function() {
  $.ajax({
    url: '/Home/GetData',
    datatype: "html",
    type: "GET",
    cache: false,
    success: function(result) {
      $('#myPartialView').empty();
      $('#myPartialView').html(result)
    },
    error: function(xhr, status, error) {
      var errorMessage = xhr.status + ': ' + xhr.statusText;
      alert('error - ' + errorMessage);
    }
  });

  return false;
});

【问题讨论】:

  • 切换该元素的“隐藏”属性。我假设您只想获取一次数据,然后将其存储在元素中,直到再次单击。

标签: jquery ajax asp.net-mvc


【解决方案1】:

我将myPartialView 缓存到一个变量中,因此我们只需查找一次。

编辑:

更改了代码以测试:empty,因此即使在初始状态下它也应该可以工作。

$('#myBtn').click(function () {
    var $myPartialView = $('#myPartialView');
    if ($myPartialView.is(':empty')) {
      $.ajax({
          url: '/Home/GetData',
          datatype: "html",
          type: "GET",
          cache: false,
          success: function (result) {
              $myPartialView.html(result);
          },
          error: function (xhr, status, error) {
              var errorMessage = xhr.status + ': ' + xhr.statusText;
              alert('error - ' + errorMessage);
          }
      });
    }
    else {
      $myPartialView.empty();
    }
    
    return false;
});

【讨论】:

  • 第一次单击按钮时,没有任何反应。之后的每一次点击都会隐藏或显示部分视图
  • 那是因为它的初始状态是visible 但它是空的。您可以将其样式设置为style="display: none"
  • 试试新版本。它会检查:empty,因此即使在初始状态下它也应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 2013-04-24
相关资源
最近更新 更多