javascript - 如何使用 jQuery 添加 DOM 元素?

标签 javascript jquery dom

我有一个函数,我目前正在使用它来显示隐藏的 div.a_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);
    }

    }); 

});

Ok, now that i have this sorted out, i have one more question,

I have another function that removes the inserted div's if a button is clicked. It's not working now that the additional divs are not loaded into the dom on pageload. How can i trigger the function to remove these now?

jQuery(function(){ // Hide Answer

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>');

编辑
您可以通过对 somefile.php 的 AJAX 调用获取信息,然后 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";
?>

编辑
好的,试试这个:

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。

关于javascript - 如何使用 jQuery 添加 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/395525/

相关文章:

javascript - 在 react 输入 onChange 中缺少此内容

jquery - 如何使用 jQuery 找到表单内的按钮?

jQuery 脚本可以在 jsfiddle 上运行,但不能在我的网站上运行?

javascript - popup.js 未在 Chrome 扩展中的 popup.html 的 head 标记内执行

javascript - 你能给我解释一下这段代码吗?

javascript - 如何在 Qualtrics 上使用 Javascript 控制播放哪些 mp3 文件?

javascript - $.isNumeric 与 isNaN

java - 使用Java递归地变换dom节点

javascript - jQuery 事件命名空间是如何工作的

javascript - 创建图像并将其附加到 div。怎么了?