-1

I have a array of contacts, with array websites (object) I would like to display clickable URL format using Jquery.

for ( var i = 0; i < contacts[contactIndex].webAddresses.length; i++) {

            var contactFieldWebsites = $(document.createElement('span')).attr({
                class : 'contactFieldWebsites'
            }).html(newOrUpdatedOrNone(contacts[contactIndex].webAddresses[i])+
                    ('href' contacts[contactIndex].webAddresses[i].url) + ' ('
                            + contacts[contactIndex].webAddresses[i].kind + ')'+'<br/>');
            contactDiv.append(contactFieldWebsites);

        }

Here I just load url whereas I would like to be able to to click on url and redirect me on selected website thx

4

2 回答 2

1

由于您有 jQuery,您可以在创建时将点击事件链接到您的 span 元素(我还将您创建 span 的方式更改为$("<span/>")):

 var contactFieldWebsites = $("<span/>").attr({class : 'contactFieldWebsites'})
 .html(newOrUpdatedOrNone(contacts[contactIndex].webAddresses[i]) + ('href' contacts[contactIndex].webAddresses[i].url) + ' (' + contacts[contactIndex].webAddresses[i].kind + ')'+'<br/>')
 .click(function() {
     location.href = "your new href goes here";
 });
 contactDiv.append(contactFieldWebsites);

这是一个演示,展示了将可点击功能添加到新创建的元素(并附加到容器)的概念:http: //jsfiddle.net/zRLfE/

于 2013-07-09T14:34:50.957 回答
1

我建议使用attr()方法来更新锚属性。

        var currentContact = contacts[contactIndex];
        for ( var i = 0; i < currentContact.webAddresses.length; i++) {
            var webAddress = currentContact.webAddresses[i];
            var contactFieldWebsites = $('<span/>')
                .addClass('contactFieldWebsites')
                .text('(' + webAddress.kind + ')');
            if (newOrUpdatedOrNone(webAddress )){
                var link = $('<a />')
                    .attr({'href': webAddress .url})
                    .text(webAddress.url)
                    .appendTo(contactFieldWebsites);
            }
            contactDiv.append(contactFieldWebsites);

        }
于 2013-07-09T14:30:48.440 回答