与jQuery动态创建img标签?
如何在表格内创建动态标签。起初创建链接,然后里面的链接创建一样,如果我有一个img标签..与jQuery动态创建img标签?
<table>
<tr>
<td>
<a>
<img />
</a>
// Add Some more when every time my function is run..? like that
// <a>
// <img/>
// </a>
</td>
</tr>
</table>
进出口使用这里面的功能,但它没有工作,帮助我。
$(document.createElement("img")).attr('Some attr');
如果你指的JQuery通过 “jquree” ,那么试试这个:
$('table tr td').append('<a href="#"><img src="/favicon.ico"/></a>');
$(document).ready(function(){
$('.any_element_you_want').html('<a href="/home" title="Home"><img src="image.png"></a>');
});
制作使用jQuery的比你中央社箱子图像元素像下面
$(document).ready(function(){
var elem = new Element('img',
{ src: 'pic.jpg', alt: 'alternate text' });
$(document).insert(elem); //here you can also make use of `append` method instead of this method
}
或
var img = new Image(1,1); ///params are optional
img.src = ''pic.jpg';
我试着这个,我认为它的工作。 – QasimRamzan 2012-04-04 07:28:11
@QasimRamzan - 如果符合您的要求,请接受并提出答案 – 2012-04-04 07:36:56
var td = $('table tr td');
td.append('<a><img src="whatever.jpg"/></a>');
好,我是不会回答这个问题,但我没有看到任何正确的答案(从我的POV):
function addElement(tdId) { // Specify the id the of the TD as an argument
$('#' + tdId).append(// Append to the td you want
$('<a></a>').attr({ // Create an element and specify its attributes
'href': '/home',
'title': 'Home'
}).append(// Also append the image to the link
$('<img />').attr({ // Same, create the element and specify its attributes
'src': 'image.png',
'width': '100px',
'height': '100px'
})
) // Close the "append image"
) // Close the "append anchor"
}
现在是一个纯粹的jQuery的答案。一个JavaScript的答案将如下:
function addElement(tdId) { // Specify the id the of the TD as an argument
// Create the DOM elements
var a = document.createDocumentFragment('a'),
img = document.createDocumentFragment('img') // See the use of document fragments for performance
// Define the attributes of the anchor element
a.href = '/home'
a.title = 'Home'
// Define the attributes of the img element
img.src = 'image.png'
img.width = '100px'
img.height = '100px'
// Append the image to the anchor and the anchor to the td
document.getElementById(tdId).appendChild(a.appendChild(img))
}
我认为js版本更具可读性。但这只是我的看法; o)。
在每次点击按钮,它会添加img标签与图像url abc.png 并添加到具有id imagediv的div。
$("button").click(function()
{
var img=$('<img id="dynamic">');
$(document.createElement('img'));
img.attr('src',"abc.png");
img.appendTo('#imagediv');
});
这很容易通过咨询官方jQuery的文档研究。 http://api.jquery.com/append/ – Patrick 2012-04-04 07:18:59
不要忘了标记答案,如果你有你想要的信息 – 2012-04-04 07:52:30