2

我有一些 javascript(以简化格式显示如下),它是来自广告服务器的“广告代码”,它在 html 页面上显示了一个广告单元。

<script type="text/javascript" src="http://adserverdomain.net;pcode=1234;city=nameofcity;suburb=nameofsuburb"></script>

javascript 有更多变量,但我刚刚展示了一个。

下面我有一个<div>我想从上面的javascript中提取变量“pcode”并使用它显示它的值

$('div').html("");

所以<div>需要用值“1234”填充。

知道我该怎么做吗?谢谢

编辑:我已经更新了网址(在 pcode 之后添加了 .net 和其他一些变量以避免混淆)。另外,我无权访问初始脚本,因此无法为其添加 id。该脚本由广告服务器生成,并且始终具有变量 pcode(具有不同的值)。只需要能够在同一个 html 页面上的另一个 div 中显示它。

4

3 回答 3

1

尝试

<script type="text/javascript" src="http://adserverdomain;pcode=1234;city=sajdhsk;suburb=asdsadas"></script>
<div id="pcode"></div>
<div id="city"></div>
<div id="suburb"></div>

然后

var pcodesrc = $('script[src^="http://adserverdomain;"]').attr('src');

$('#pcode').html(pcodesrc.match(/pcode=(.+?)(?=(;|$))/)[1])
$('#city').html(pcodesrc.match(/city=(.+?)(?=(;|$))/)[1])
$('#suburb').html(pcodesrc.match(/suburb=(.+?)(?=(;|$))/)[1])

演示:小提琴

或者

$('#pcode').html(pcodesrc.match(/pcode=([^;]+)/)[1])
$('#city').html(pcodesrc.match(/city=([^;]+)/)[1])
$('#suburb').html(pcodesrc.match(/suburb=([^;]+)/)[1])

演示:小提琴

于 2013-09-02T07:40:08.930 回答
0

用 url 试试这个。实际上,下面的代码从 url 查询字符串中获取数据。编辑它并给出你的 url。

function getUrlVars() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

var me = getUrlVars()["pcode"];
于 2013-09-02T07:40:06.487 回答
0

试试这个朋友

function getvalues()
    {
        var values = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { values[key] = value;});
        return values;
    }

每当你想使用它

var value = getvalues()["pcode"];

使用此值放入您的 html 元素

于 2013-09-02T07:43:24.017 回答