开发者

How can I use 'window.location.href' in a jQuery HTML insertion or wrap?

I'm trying to insert a link into an empty < a > that has the id "popup". The link will open the current page in a popup box (with parameters I'll define later). I'm trying to string together the HTML needed to make a hyperlink plus the JS variable 'window.location.href' -- how can thes开发者_JAVA百科e be strung together? i.e. how do I fix this to make it work, or rewrite it as a function with 'window.location.href' as a variable:

$("#popup").html('<a href=' . window.location.href . '>open popup</a>');


Like this:

$("#popup").html($('<a />', { href: window.location.href, text: 'open popup' }));

Or for the popup:

$("#popup").html($('<a />', { 
  href: window.location.href, 
  text: 'open popup',
  target: '_blank'
}));

Or, using window.open() for parameters:

$("#popup").html($('<a />', { 
  href: '#', 
  click: function() { window.open(window.location.href, 'popup', 'params'); }
}));

There were 2 problems with your original approach:

$("#popup").html('<a href=' . window.location.href . '>open popup</a>');
  1. Use + to concatenate strings
  2. You need quotes around the attribute

Like this:

$("#popup").html('<a href="' + window.location.href + '">open popup</a>');


btw: in javascript you combine strings with a + instead of . (PHP, right?):

var something = 'Hello' + ' ' + 'World'; // => 'Hello World'


$("#popup").attr("href",window.location.href).attr("target","_blank").text("Open Popup");


This will change the link, so the href is the same.

$("#popup").attr('href',window.location.href);

e.g.

<a id="popup" href="">popup</a>

becomes

<a id="popup" href="yourcurrenturl">popup</a>

EDIT:

To give you a little inspiration for other techniques for popups (forgive me if this if this code doesn't work, I just whipped to together quickly)

HTML

 <a href="http://www.developertipoftheday.com" rel="popup" target="alexsite">open alex site in popup</a>

JavaScript

$("a[rel = 'popup']").click(function (event) {

    var popupWindow= window.open($(this).attr("href"), $(this).attr("target"), "status=true,toolbar=false,menubar=false,location=false,width=1018,height=792")

    if (popupWindow=== null) {

        alert("A messasge to inform the user, that the popup has been blocked");
    }

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜