开发者

How can you add an ID to dynamically generated href?

开发者 https://www.devze.com 2023-04-09 10:31 出处:网络
how can you add an ID to a link generated like this? function addElement(list, pos) {开发者_JAVA百科

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

精彩评论

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