Javascript 使用jquery动态创建元素
我正在尝试使用jquery创建元素。当我点击一个链接时,我想创建一个元素“p”,给它一些文本,然后把它放在我的一个div中。另外,我想检查点击了哪个链接,这样我就可以把创建的“p”放在正确的div中。有没有解决我哪里做错了的方法 Javascript/JqueryJavascript 使用jquery动态创建元素,javascript,jquery,html,createelement,Javascript,Jquery,Html,Createelement,我正在尝试使用jquery创建元素。当我点击一个链接时,我想创建一个元素“p”,给它一些文本,然后把它放在我的一个div中。另外,我想检查点击了哪个链接,这样我就可以把创建的“p”放在正确的div中。有没有解决我哪里做错了的方法 Javascript/Jquery $(document).ready(function () { function createElement() { var a = $("#menu").find('a').each(function(){ if(a
$(document).ready(function () {
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
}
$("#menu").find('a').each(function () {
$(this).click(function () {
createElement();
});
});
createElement();
});
HTML
Inl1-1
函数createElement(){
var a=$(“#菜单”).find('a').each(函数(){
如果(a=“l1”){
var p=$(“”);
p、 文本(“Hej”);
$(“#contentl1”)。追加(p);
}
});
}
我知道回答您的问题并不现实,但很难将此作为评论:
var a = $("#menu").find('a').each(function(){ <-- this "a" will only be created after the each completes
if(a == "l1"){ <-- this "a" that you are verifying is a global variable
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
var a=$(“#menu”).find('a')。每个(function(){这里是使用jQuery将带有文本“Hej”的新
元素添加到#contentl1
的最佳方法:
$("<p />", { text: "Hej" }).appendTo("#contentl1");
$(“”,{text:“Hej”});
首先,单击功能可以这样完成,而不必使用。find():
.each()循环的执行方式如下:
$('#menu a').each(function () {
var aId = $(this).attr('id');
var contentId = content + aId;
$(contentId).append('<p>Hej</p>');
})
$('#菜单a')。每个(函数(){
var-aId=$(this.attr('id');
var contentId=内容+辅助;
$(contentId).append(“Hej”);
})
类似于
$('#菜单')。在('click','a',函数(e)上{
e、 预防默认值();
$(“”).text($(this.text()).appendTo(“#content”+this.id);
});
试试这个脚本,它会将文本放在正确的div
中
$(document).ready(function () {
$("#menu").find('a').each(function () {
$(this).on('click',function () {
$("#content"+$(this).attr("id")).append("<p>link "+$(this).attr("id")+" is clicked</p>");
});
});
});
$(文档).ready(函数(){
$(“#菜单”)。查找('a')。每个(函数(){
$(此).on('click',函数(){
$(“#content”+$(this.attr(“id”)).append(链接“+$(this.attr(“id”)+”被单击“”);
});
});
});
首先..您的var text=$(document.createElement('p');
遗漏了一个结束括号您是否在函数中使用了一个变量,该函数的返回值应为variable?var a=$(“#菜单”).find('a')。each(function(){if(a='l1”){
$("<p />", { text: "Hej" }).appendTo("#contentl1");
$('#menu a').click(function() { }
$('#menu a').each(function () {
var aId = $(this).attr('id');
var contentId = content + aId;
$(contentId).append('<p>Hej</p>');
})
$('#menu').on('click', 'a', function(e) {
e.preventDefault();
$('<p>').text($(this).text()).appendTo('#content'+this.id);
});
$(document).ready(function () {
$("#menu").find('a').each(function () {
$(this).on('click',function () {
$("#content"+$(this).attr("id")).append("<p>link "+$(this).attr("id")+" is clicked</p>");
});
});
});