开发者

How can you add an ID to dynamically generated href?

how can you add an ID to a link generated like this?

function addElement(list, pos) {开发者_JAVA百科
    var linkUrl = productList.products[pos].productLink;
    var linkItem = document.createElement('a');
    linkItem.setAttribute('href', linkUrl);

The previous code generates the following link

<a href="***/details.page?productId=3"><img src="***/topseller_main_en_1.png"></a>


Try this:

function addElement(list, pos) { 
    var linkUrl = productList.products[pos].productLink; 
    var linkItem = document.createElement("a"); 
    if (linkItem){
        linkItem.id = "foo";
        linkItem.href = linkUrl;
    }
}

You can also do this in jQuery like this:

function addElement(list, pos) { 
    var linkUrl = productList.products[pos].productLink; 
    var linkItem = document.createElement("a"); 
    if (linkItem){
        linkItem.attr({ id : "foo", href : linkItem });
    }
}

Here's an even shorter way:

$("<a>").attr({ id : "foo", href : linkUrl });

Then just append it to an element in the document.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜