简体   繁体   中英

Appending a link in JavaScript for mobile browsers

I tried searching for my problem, but couldn't find a solution. Sorry if this is already posted.

I have a dynamically created href link using append, but it does not work on mobile Safari and mobile Chrome (other than ipad). The link works fine on all desktop browsers I have tested or if I choose "Request desktop site" on a mobile device. This is what I am doing:

I am using append to create some elements and one of them contains my link. The information is simply taken from a json array.

HTML:

<ul id="structure"></ul>    

Javascript:

function createStructure(i){

    $(structure).append($('<ul> \
    <li data-type="media" data-url=\"' + properties[i].image + '\"data-target="_blank"></li> \
    <li data-thumbnail-path=\"' + properties[i].thumbnail + '\"></li> \
    <li data-info=""> \
        <p class="mediaDescriptionText">Link to map: <a class="gmaplink" target="_blank" rel="external" href="http://www.maps.google.com/?q=' + properties[i].Address +'">Click Here</a>.</p> \
    </li></ul>'));  
}

The link is to google maps, but it does not work on mobile version of Safari and Chrome (on mobile devices). I also tried to add an .on() to make sure the click event would be detected:

$(document).on('click', '.gmaplink', function(){
    console.log("link working: " + this.href);
    window.open(this.href, '_blank');
});

But this code also fails, even though I see that it gets executed with my log (works everywhere other than mobile browsers). However, if I remove the append and simply have the html structure, the links are working on mobile... So this tells me the issue might be with the append.

My question is: what is the proper way to include a link (href) when using append and on mobile browsers.

Thank you!

Try the following code, because you had some weird escape characters when not needed, and you didn't encode the q parameter in your URL, and you didn't use the right selector #structure :

function createStructure(i){

    $('#structure').append($('<ul>' +
    '<li data-type="media" data-url="' + properties[i].image + '" data-target="_blank"></li>' +
    '<li data-thumbnail-path="' + properties[i].thumbnail + '"></li>' +
    '<li data-info="">' +
        '<p class="mediaDescriptionText">Link to map: <a class="gmaplink" target="_blank" rel="external" href="http://www.maps.google.com/?q=' + encodeURIComponent(properties[i].Address) +'">Click Here</a>.</p>' +
    '</li>'+
'</ul>'));

}

Edit : Didn't see the question was asked a year ago... =_=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM