简体   繁体   English

jQuery添加DOM元素

[英]jQuery Adding DOM Elements

This may be a simple answer, but I'm trying to add a dom-created element (ie document.createElement(...) ) to a jQuery Selector. 这可能是一个简单的答案,但是我试图将一个dom创建的元素(即document.createElement(...) )添加到jQuery选择器中。

jQuery has a great assortment of functions for adding html jQuery有各种各样的功能可以添加html

  • .html(htmlString) html的(htmlString)
  • .append(htmlString) .append(htmlString)
  • .prepend(htmlString) .prepend(htmlString)

But what i want to do is add a dom OBJECT 但是我想做的是添加一个dom对象

var myFancyDiv = document.createElement("div");
myFancyDiv.setAttribute("id", "FancyDiv");

// This is the theoretical function im looking for.
$("#SomeOtherDiv").htmlDom(myFancyDiv); 

Try this: 尝试这个:

$("#SomeOtherDiv").append($(myFancyDiv)); 

Wrapping the DOM element in $(...), I'd expect you could add it with any of the jQuery DOM manipulation functions that take a jQuery element collection. 将DOM元素包装在$(...)中,我希望您可以将其与任何采用jQuery元素集合的jQuery DOM操作函数一起添加。

这应该做的!

  $("#SomeOtherDiv").append('<div id="FancyDiv"></div>')); 

通过完全切掉jQuery,可以使事情变得更简单,更快捷:

document.getElementById("SomeOtherDiv").appendChild(fancyDiv);

This will work in jQuery 1.4 这将在jQuery 1.4中工作

$("<div/>",{
    id: 'FancyDiv'
}).appendTo("#SomeOtherDiv");

http://api.jquery.com/jQuery/#jQuery2 http://api.jquery.com/jQuery/#jQuery2

You can try this way: 您可以这样尝试:

$("<div/>", {

  // PROPERTIES HERE

  text: "Click me",

  id: "example",

  "class": "myDiv",      // ('class' is still better in quotes)

  css: {           
     color: "red",
     fontSize: "3em",
     cursor: "pointer"
  },

  on: {
    mouseenter: function() {
      console.log("PLEASE... "+ $(this).text());
    },
    click: function() {
      console.log("Hy! My ID is: "+ this.id);
    }
  },

  append: "<i>!!</i>",

  appendTo: "body"      // Finally, append to any selector

}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM