使用 JavaScript / jQuery 中的按钮单击动态添加 div

新手上路,请多包涵

如何在 JavaScript/jQuery 中单击按钮时动态添加 div?我想要具有类“listing listing_ad job”的 div 的所有格式。

这是我使用 jQuery 尝试的代码。

 $('#btnAddtoList').click(function(){
	var newDiv = $('<div class="listing listing_ad job"><h4><a>Some text</a></h4> </div>');
  //newDiv.style.background = "#000";
  document.body.appendChild(newDiv);
});
 .listing {
  border-bottom: 1px solid #ddd;
  float: left;
  padding: 0 0 5px;
  position: relative;
  width: 559px;
}

.listing:hover {
  background: #f5f5f5 none repeat scroll 0 0;
  border-bottom: 1px solid #ddd;
  cursor: wait;
}

a:hover {
  color: #ff5050;
}

.subtitle {
  width: 430px;
  font-weight: normal;
  font-size: 12px;
  font-family: Arial;
  color: #7f7f7f;
}

.info {
  float: left;
  margin: 10px 15px 5px;
  min-width: 500px;

  clear: both;
  color: #7f7f7f;
  margin: 15px 44px 15px 0;
  overflow: hidden;
}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAddtoList">
Add to list
</button>

<div class="listing listing_ad job">
  <h4>
   <a>
  Excellent Opportunity For Internship at Diamond
  </a>
  </h4>
  <div class="subtitle">
  Lahore, Punjab
  </div>
  <div class="info">
  This is Info / Description.
  </div>
</div>
<!-- ************************ -->

<div class="listing listing_ad job">
  <h4>
  <!-- Src: http://jobs.mitula.pk/internship-program-lahore-jobs -->
  <a>
  Excellent Opportunity For Internship at Diamond
  </a>
  </h4>
  <div class="subtitle">
  Lahore, Punjab
  </div>
  <div class="info">
  This is Info / Description.
  </div>
</div>

Jsfiddle:http: //jsfiddle.net/mr4rngbL/3/

原文由 Asad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 564
2 个回答

是的,您可以 - 通过将 jQuery 添加到文档的脚本中,并将代码 document.ready

 $(function() {
    $('#btnAddtoList').click(function(){
        var newDiv = $('<div class="listing listing_ad job"><h4><a>Some text</a></h4> </div>');
      //newDiv.style.background = "#000";
       $('body').append(newDiv);
    });
});

示例 http://jsfiddle.net/mr4rngbL/5/

您在评论中提出的问题示例:http: //jsfiddle.net/mr4rngbL/6/

最后 一个例子是根据你在评论中的要求:http: //jsfiddle.net/mr4rngbL/7/

原文由 Alon Eitan 发布,翻译遵循 CC BY-SA 3.0 许可协议

Here 纯 JavaScript 解决方案

 function addDiv(parent_div, content, attrs) {
  var div = document.createElement('div');
  var parent = document.getElementById(parent_div);

  for (var key in attrs) {
    if (attrs.hasOwnProperty(key)) {
      div.setAttribute(key, attrs[key]);
    }
  }
  div.innerHTML = content;
  if (parent) {
    parent.appendChild(div);
  }
}

var button = document.getElementsByTagName('button')[0];
if (button) {
  button.addEventListener('click', function() {
    // change dynamically your new div
    addDiv('parent', 'hi', {
      'class': 'someclass someclass',
      'data-attr': 'attr'
    });
  });
}
 <button>Add Div</button>
<div id="parent">

</div>

原文由 0xdw 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题