jQuery中的元素属性

时间:2017-08-31 21:05:48

标签: javascript jquery

我是jQuery的新手。所以在javascript中你可以创建一个div并给它自己的属性如下:

var msgbubble = document.createElement('div');
  msgbubble.marginTop="10px";
  msgbubble.style.backgroundColor="#ccc";

无论如何我可以在jquery中创建这样的元素以及如何追加它。 感谢。

4 个答案:

答案 0 :(得分:0)

jQuery只使用 .append() 方法,虽然它也有.appendTo(),它的功能相同,但两者在语法上是不同的。

$("span").append("Appended text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span></span>

实际样式化的屁股,可以通过 .css() 属性直接完成:

el.css('margin-top', '10px');
el.css('background-color', '#ccc');

希望这有帮助! :)

答案 1 :(得分:0)

创建div,设置属性和追加它的一个小例子:

var msgBubble = $('<div></div>');

// set css properties
msgBubble.css({
  'margin-top': '10px',
  'background': '#ccc'
});

// or set html attributes
msgBubble.attr({
  'data-foo': 'bar'
});

// add some text so it actually has a height
msgBubble.text('message bubble');

$('span').append(msgBubble);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>

答案 2 :(得分:0)

使用open github feature request,您可以传递html文本,然后创建一个元素。

var element = jQuery('<div></div>');

如果为属性jQuery(html)传递了第二个参数,它将使用它们并在元素上设置它们。

var element = jQuery('<div></div>',{
  css:{
    marginTop:'10px',
    backgroundColor:'#ccc'
  }
});

要追加,您可以使用jQuery(html, attributes)append()等各种方法。

element.appendTo(document.body);

因此,如果你想创建你的元素,设置样式,并将元素一次性附加,你可以将所有这些结合起来:

jQuery('<div></div>',{
  css:{
    marginTop:'10px',
    backgroundColor:'#ccc'
  },
  text:"Some text to go into the element"
}).appendTo(document.body);

答案 3 :(得分:0)

检查此代码段以创建具有一些css属性的div元素,并使用jQuery设置其他属性。

&#13;
&#13;
$(document).ready(function() {
  let elem = $("div");  // create div element and reference it with `elem` variable
  
  // Set css properties to created element
  elem.css(
   {
    'background-color': 'red', 'marginTop': '50px',
    'height': '200px', 'width': '200px'
   }
  );

  // Set attribute to created element
  elem.prop(
    {
      'id':'div1', 'class': 'myClass'
     }
    );
  
  $('body').append(elem);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

有关jQuery的更多信息,请访问https://www.w3schools.com/jquery

希望,这个小代码片段适合你.. :):)