使用JavaScript读取JavaScript src属性的GET值

时间:2014-03-19 16:57:02

标签: javascript php html

我正在使用此代码,我的文件名是ads.js

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*?)[#.]/gi, function(m, key, value) {
        vars[key] = value;
    });
    return vars;
}
var pic = getUrlVars()["pic"];
var random_ads_array = ["visitors.jpg", "payouts.jpg", "logos-icon.jpg"];

function getRandomAds(imgAr, path) {
    path = path || 'buycimg/'; // default path here
    var num = Math.floor(Math.random() * imgAr.length);
    var img = imgAr[num];
    var imgStr = '<a href="http://appricart.com/' + pic + '.html"><img src="' + path + img + '" alt = ""></a>';
    document.write(imgStr);
    document.close();
}

在html部分我正在使用此代码

<script type="text/javascript" src="ads.js?pic=45bus67"></script>
<script type="text/javascript">getRandomAds(random_ads_array);</script>

Out put显示图像但未显示正确的链接 输出就像这样

  

http://appricart.com/undefined.html

我想要展示

  

http://appricart.com/45bus67.html

与此感谢相关的帮助

2 个答案:

答案 0 :(得分:0)

也许你可以给它一个ID - 然后:

src = document.getElementById("scriptId").getAttribute("src");
src = src.split("?pic="); 
src = src[1];

瞧!您可以使用src

执行所需操作

答案 1 :(得分:0)

为什么不将pic值放入函数中?

<script type="text/javascript" src="ads.js"></script>
<script type="text/javascript">getRandomAds(random_ads_array, "45bus67");</script>

ads.js

var random_ads_array = ["visitors.jpg", "payouts.jpg", "logos-icon.jpg"];
function getRandomAds(imgAr, pic, path) {
    path = path || 'buycimg/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '<a href="http://appricart.com/' + pic + '.html"><img src="' + path + img + '" alt = ""></a>';
    document.write(imgStr); document.close();
}