dynamically create element using jquery

旧城冷巷雨未停 提交于 2019-12-04 05:22:10

Here is the best way to add new <p> element with text "Hej" to #contentl1 using jQuery:

$("<p />", { text: "Hej" }).appendTo("#contentl1");
function createElement() {
  var a = $("#menu").find('a').each(function(){
    if(a == "l1"){
    var p = $("<p>");
    p.text("Hej");
    $("#contentl1").append(p);
    }
  });
}

For a start the click function can be done like this instead of having to use .find():

$('#menu a').click(function() { }

The .each() loop can be done like:

$('#menu a').each(function () {
    var aId = $(this).attr('id');
    var contentId = content + aId;
    $(contentId).append('<p>Hej</p>');
})

I know it doesn't realate to answering your question but it is hard to leave this as a comment:

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");
    }
  });

You can try this to solve your issue:

function createElement() {
  if($(this).attr("id") == "l1"){
   $("#contentl1").append('<p>hej</p>');
  }
}

$("#menu a").each(function () {
    $(this).click(function () {
        createElement.apply(this);
    });
});

Something like this fiddle?

$('#menu').on('click', 'a', function(e) {
    e.preventDefault();
    $('<p>').text($(this).text()).appendTo('#content'+this.id);
});

try this script, it'll do place the text in correct 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>");
    });
});


});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!