如何使用 jQuery 添加 DOM 元素?

2024-02-09

我有一个当前用来显示隐藏 div.type 的函数

我怎样才能修改这段代码,而不是在隐藏的div中淡出, 我可以将新的 div 添加到 DOM



jQuery(function(){   // Add Answer

    jQuery(".add_answer").click(function(){
      if(count >= "4"){
        alert('Only 4 Answers Allowed');
        }else{
      var count = $(this).attr("alt");
      count++;
      $(this).parents('div:first').find('.a_type_'+count+'').fadeIn();
      $(this).attr("alt", count);
    }

    }); 

});
  

好吧,现在我已经解决了这个问题,我还有一个问题,

我有另一个函数,如果单击按钮,则会删除插入的 div。 现在它不起作用,因为页面加载时附加的 div 没有加载到 dom 中。 我现在如何触发删除这些的功能?

jQuery(function(){ // 隐藏答案

jQuery(".destroy_answer").click(function(){
  $(this).parents("div:first").fadeOut(function (){ $(this).remove() });
   var count = $(this).parents('div:first').parents('div:first').find('.add_answer').attr("alt");
   count--;
   $(this).parents('div:first').parents('div:first').find('.add_answer').attr("alt", count);

}); 

});


将其添加到最后一个 div 之后怎么样?

$('.a_type:last').insertAfter('<div class="a_type">content</div>');

edit
您可以通过 AJAX 调用 somefile.php 来获取信息,然后 somefile 应该在 div 中返回您想要的内容:

$.get('path/to/somefile.php', function(data){
 $('.a_type:last').insertAfter('<div class="a_type">' + data + '</div>');
});

Somefile.php 应该是这样的:

<?php
 session_start();
 $sessiondata = $_SESSION['data'];
 echo "Whatever you type here will come inside the div bla bla $sessiondata";
?>

edit
好的,试试这个:



jQuery(function(){ // Add Answer

jQuery(".add_answer").click(function(){
  if(count >= "4"){
    alert('Only 4 Answers Allowed');
    }else{
  var count = $(this).attr("alt");
  count++;
  $('.a_type_'+count-1+'').insertAfter(' 
       Place content back here');
  $(this).attr("alt", count);
}

});

});
  

如果您仍然需要,只需混合 AJAX 即可。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 jQuery 添加 DOM 元素? 的相关文章

随机推荐