在jQuery中向动态链接元素添加动态href属性

问题描述:

我有一个项目,我使用*的API来检索一些内容。我试图更新一个“点击这里阅读更多链接”动态,但我似乎并没有得到它,我检查了我的代码。这里是我的搜索功能:在jQuery中向动态链接元素添加动态href属性

searchEntry: function (entry) 
    { 
     var linker = "http://en.wikipedia.org/wiki/"+entry; 
     var link = $('<div id="more" contenteditable="true"><p><a href="#" id="morelink">Click here</a> to read more.</p></div>'); 
     $("div#more a").attr("href", linker); 
     console.log(link); 
     $.getJSON(wikiSearch.wbase+"action=parse&format=json&prop=text&section=0&page=" + entry + "&redirects&callback=?", function(data) 
     { 

      if (!data.error) 
      { 
       var markup = data.parse.text["*"]; 
       if (typeof markup !== "undefined") 
       { 
        $("#entry").text(entry).show(); 
        var blurb = $('<div id="articleText"></div>').html(markup); 

        // remove links as they will not work 
        blurb.find('a').each(function() { $(this).replaceWith($(this).html()); }); 

        // remove any references 
        blurb.find('sup').remove(); 

        // remove cite error 
        blurb.find('.mw-ext-cite-error').remove(); 
        $('#article').html($(blurb).find('p')); 

        $("#article").append(link); 
        // console.log(markup); 
       } 
      } 
      else 
      { 
       $("#warning").text(data.error.info).show(); 
      } 
      $(".spinner").hide(); 
     }); 
     $("#article").show(); 
     // if($("#article").show()) 
     // { 
     // wikiSearch.showMore(); 
     // } 
    }, 

你的链接包含在可变link但尚未连接到DOM呢,所以当你尝试搜索对于它来说,使用$("div#more a")什么也找不到,因为jQuery正在搜索你的页面的HTML,而不是你动态添加到某个变量的HTML。

你有两个选择:

1)连结放在您的网页,而不是试图动态创建的HTML,所以你可能只是这样做:

var link = $('#more a'); 
link.attr('href', linker); 

2 )如果必须动态创建,请在创建时添加href属性,然后确保将其附加到DOM。就像:

var linker = "http://en.wikipedia.org/wiki/" + entry; 
var link = $('<div id="more" contenteditable="true"><p><a href="' + linker + '" id="morelink">Click here</a> to read more.</p></div>'); 

// The link is now only stored in the variable we created. 
// We need to add it to our page. You can replace 'body' with the parent element that the link should be added to. 
$('body').append(link); 
+1

非常感谢..它工作 – dejijaye 2014-09-26 07:01:11

+0

很高兴帮助:) – 2014-09-26 17:40:33

我相信这是因为jQuery的$(“”)应该是元素选择,不应该有任何HTML结构了。 $(“div#more a”)找不到任何东西,因为(据我所知),代码实际上并不在jQuery所搜索的DOM中。难道你不能这样做:

var link = '<div id="more" contenteditable="true"><p><a href="'+ linker + '" id="morelink">Click here</a> to read more.</p></div>'; 

然后将其附加到您的HTML。

首先,使用.prop而不是.attr的(方法签名相同)

其次,标签不网页上,当你试图操纵它的href =,而只有它的存在,作为字符串变量存在。尝试设置链接的href属性,当你创建像这样的变量:

 var hrefLink = "http://en.wikipedia.org/wiki/"+entry; 
    var link = $('<div id="more" contenteditable="true"><p><a href=' + hrefLink + ' id="morelink">Click here</a> to read more.</p></div>');