【问题标题】:jquery hide not working for same div class after ajax call?ajax调用后jquery隐藏不适用于同一个div类?
【发布时间】:2014-02-01 00:17:36
【问题描述】:

1.这是我的代码,我有一个 div 类内部,它使用 ajax 调用动态加载 在ajax调用之后,如果我点击隐藏按钮,它就不起作用了。

但它在 ajax 请求之前工作得很好。

所以为了克服我只是添加一个外部 div 并隐藏该 div 这次它可以工作.. 不知道为什么?

$( "#inner" ).replaceWith( data );  /*and*/  $( "#inner" ).hide();   //not working


$( "#inner" ).replaceWith( data );    /*and*/     $( "#outer" ).hide();  //working

为什么我们不能使用同一个 div 类?

<html>
  <div id="outer">
  <div id="inner">
    <br /> <br /> <br />
  <div>  <input type="button" value="signup"  onclick="changeval();"/>
  </div>
  <br /> <br />  
  </div>
  </div>
  <input type="button" value="hide" onclick="onhide();"/>    
  <script language="javascript"> 
   function changeval(context)
   {          
     var typeval="sdsf";
     var url="sdfsdf";
     $.ajax({
        type:'POST',
        url:'htp://sscs/registration',
        data:'&typeval='+typeval+'&url='+url,
        success:function(data) { 
          $( "#inner" ).replaceWith( data );           
        }        
      });         
    }
    function onhide()
    {
      $( "#inner" ).hide();
    }
  </script>

【问题讨论】:

  • 尝试使用 $("#inner").replaceWith($('#inner',data));
  • 尝试 .html() 而不是 replaceWith()
  • 是的,它起作用了,但我想知道为什么当我们使用替换时它不起作用

标签: javascript jquery html ajax


【解决方案1】:

在您调用 ajax 之后,#inner-div 不再存在。您正在用您的 ajax 请求的响应替换它。

您可以使用$("#inner").html(data); 保留 div,然后在收到回复后将其隐藏。

【讨论】:

  • 上下文错误,抱歉。应该是 html()。
【解决方案2】:

它不起作用,因为您替换了&lt;div id="inner"&gt;

包括 div 及其 ID。 &lt;div id="outer"&gt; 仍然存在,所以你的其他隐藏工作,它仍然发现 div

【讨论】:

    【解决方案3】:

    使用.html()

     $("#inner").html(data);
    

    而不是.replaceWith()

    用提供的新内容替换匹配元素集中的每个元素,并返回被移除的元素集。

    DEMO of replaceWith,这里你可以看到第二类的div被替换为输入内容。

    【讨论】:

      【解决方案4】:

      这样使用:

      $( "#inner" ).replaceWith( function(){
          return $(this).data();
      } );
      

      【讨论】:

        猜你喜欢
        • 2013-01-18
        • 2014-03-08
        • 2017-12-23
        • 1970-01-01
        • 2019-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多