好吧,我不打算回答这个问题,但我没有看到任何正确的答案(来自我的 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)。