[英]Appending to an element in JQuery
I have set up an array of elements containing the alphabet and am trying to append each value as a hyperlink using jquery. 我建立了一个包含字母的元素数组,并尝试使用jquery将每个值附加为超链接。 I can see my values in the array, but on my page they are showing up as undefined.
我可以在数组中看到我的值,但是在我的页面上它们显示为未定义。 Can someone shed a little light?
有人可以照亮一点吗? thanks.
谢谢。
<p id="alphabet"><a href="#" class="alphaChar"></a></p>
<script>
var alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "W", "X","Y","Z"];
$.each(alph, function(index, value){
$("a .alphaChar").append().html( "<a href='"#"' class='alphaClass'> " + alph.val + "</a>" );
});
</script>
a number of problems, 很多问题
Use value
instead of alph.val, 使用
value
代替alph.val,
your selector was wrong, (You were looking for children with class alphachar) 您的选择器有误,(您正在寻找带有alphachar类的孩子)
$("a.alphaChar")
and your .append().html(..)
was wrong -you can chain functions in JQuery, so what you were actually doing was "Append nothing, and THEN set the HTML of the entire element to ...". 并且您的
.append().html(..)
是错误的-您可以在JQuery中链接函数,因此您实际要做的是“不添加任何内容,然后将整个元素的HTML设置为...”。
$("a.alphaChar").append( < HTML GOES HERE > );
See this fiddle http://jsfiddle.net/jFIT/wW5CZ/ 看到这个小提琴 http://jsfiddle.net/jFIT/wW5CZ/
var alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "W", "X", "Y", "Z"];
$.each(alph, function (index, value) {
console.log(value);
$("a.alphaChar").append("<a href='\"#\"' class='alphaClass'> " + value + "</a>");
});
Rather than appending it a loop, build your entire DOM element and append at the end: 而不是将其附加到循环中,而是构建整个DOM元素并在末尾附加:
var html = ""
$.each(alph, function(index, value){
html += "<a href='#' class='alphaChar'> " + value + "</a>" );
});
$("a.alphaChar").append(html);
There is some syntax error in your code I think you want to do this : 您的代码中存在一些语法错误,我认为您想这样做:
JavaScript: JavaScript的:
var alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "W", "X","Y","Z"];
$.each(alph, function(index, value){
$("a.alphaChar").append("<a href='#' class='alphaClass'> " + value + "</a>" );
});
Use this code 使用此代码
var alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P","Q", "R", "S", "T", "U", "W", "X","Y","Z"];
for (var i=0; i < alph.length; i++) {
$("a .alphaChar").append($("<a href='#' class='alphaClass'>" + alph[i] + "</a>" ));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.