[英]jQuery adding new DOM elements having attributes within an element of specific id
Is there a methodToCreate
in jQuery which could be written as 是否有一个jQuery中的methodToCreate
可以写成
$("#someId").methodToCreate("tagName", ".className");
where an element with tag tagName
would be added and given a class className
and that too inside a specific element which would have an id someId
? 在哪里添加一个带有tag tagName
的元素,并给出一个类className
,并且在一个具有id someId
的特定元素中也是someId
?
$("<tag></tag>").addClass("className").attr({id: 'someId'}).appendTo( "body" )
这是和单独设置所有属性的示例。
As pointed out such function doesn't exist, but you could always create one . 正如所指出的那样,这种功能不存在,但你可以随时创建一个。
(function( $ ){
$.fn.methodToCreate= function(tagName,className,id) {
$(id).append("<"+tagName+" "+"class="+"\'"+className+"\'>"+"SampleContent"+"</"+tagName+">");
return this;
};
})( jQuery );
and you can call this whenever you want in the following manner : 你可以按照以下方式随时调用它:
$(document).ready(function(){
$(document).methodToCreate('p','sampleClass','#someId');
});
Using this function( methodToCreate
) you can dynamically pass the tagName
, className
and id
of the element that you want to append to. 使用此函数( methodToCreate
),您可以动态传递要追加的元素的tagName
, className
和id
。
Here is the working fiddle : https://jsfiddle.net/varunsinghal65/udrxeg9m/1/#&togetherjs=TBEnLAnNzJ 这是工作小提琴: https : //jsfiddle.net/varunsinghal65/udrxeg9m/1/#&togetherjs=TBEnLAnNzJ
Using jQuery you can create an element 使用jQuery,您可以创建一个元素
var el = $('<tagName class="className"/>');
and then add it to a container 然后将其添加到容器中
$('#someId').append(el);
$('#someId').append('<tagname class="className"></tagname>');
如果您将类存储在变量中(例如myClass
),请不要忘记引用它:
$('#someId').append('<tagname class="' + myClass + '"></tagname>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.