最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: $(element).text() doesn't work - Stack Overflow

programmeradmin3浏览0评论

I am dynamically generating content - div's with links in them. Link should bring up a popup containing link's text when clicked (showMyText function). Instead I get an empty string :(

Why isn't this working? I've searched Stackoverflow and jQuery API and it should work.

function a(){
    var div=document.createElement("div");
    div.innerHTML='<a class="aClass" href="javascript:showMyText(this)">Link Text</a>';

    var parent_div=document.getElementById('dinamicni_div');
    parent_div.appendChild(div);    
}

function showMyText(link){
    var txt=$(link).text();
    alert(txt);
}

I am dynamically generating content - div's with links in them. Link should bring up a popup containing link's text when clicked (showMyText function). Instead I get an empty string :(

Why isn't this working? I've searched Stackoverflow and jQuery API and it should work.

function a(){
    var div=document.createElement("div");
    div.innerHTML='<a class="aClass" href="javascript:showMyText(this)">Link Text</a>';

    var parent_div=document.getElementById('dinamicni_div');
    parent_div.appendChild(div);    
}

function showMyText(link){
    var txt=$(link).text();
    alert(txt);
}
Share Improve this question asked Apr 21, 2012 at 21:17 c0dehunterc0dehunter 6,16018 gold badges81 silver badges151 bronze badges 2
  • Because link is no dom node, has no valid selector or there is no element which matches the selector. – Andreas Commented Apr 21, 2012 at 21:19
  • How can i then access the (a href) element which called the function? Using keyword this it doesn't work either (I think this is referencing to function itself) – c0dehunter Commented Apr 21, 2012 at 21:21
Add a ment  | 

4 Answers 4

Reset to default 3

If you're using jQuery to get the text() why not use it for everything else too?

function a() {
    var $div = $("<div></div>");
    var $a = $("<a></a>")
        .attr("href", "#")
        .addClass("aClass")
        .text("Link text")
        .appendTo($div);

    $div.appendTo("#dinamicni_div");
}

$("#dinamicni_div").on('click', '.aClass', function() {
    alert($(this).text());
});

Example fiddle

Change your code to:

div.innerHTML='<a class="aClass" onclick="showMyText(this)">Link Text</a>';

jsFiddle example.

I would take a slightly different approach and use the "live" method which will allow you to bind a click event to the dynamically created element once it is inserted into the DOM

$(document).ready(function(){
  $('#dinamicni_div').html('<a class="aClass" href="#">Link Text</a>');
  $(".aClass").live('click',function(){
    alert($(this).text());
  });
});

I find that text() stops working after the user manually edits the text area. val() continues to work as expected.

发布评论

评论列表(0)

  1. 暂无评论