使用JavaScript更新位置(src)中的参数

时间:2011-08-25 04:15:46

标签: javascript dom parameter-passing replace src

如何解析status ='log-out'的值到它下面的3个标签,更新login_status ='已注销'的值?

<script type="text/javascript">
      window.ndm = window.ndm || {};
      window.ndm.cam = {'status':'logged-out'};
</script>

<script src="http://foo.com/adserver/ndm/js.php?position=header-ad&amp;section_id=NEWS&amp;login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=middle-ad&amp;section_id=NEWS&amp;login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=footer-ad&amp;section_id=NEWS&amp;login_status=SUBSCRIBER"></script>

请记住,页面上还有大量其他脚本标记,以便识别相关标记。我有这个功能。

function getScriptSourceName(name){
var scripts = document.getElementsByTagName('script');
for (i=0;i<scripts.length;i++){
    if (scripts[i].src.indexOf(name) > -1)
        return scripts[i].src;
}}

因此,为了找到我想要的相关脚本标签,我调用了函数 - getScriptSourceName('foo.com');

如何更新login_status参数的值以使用最顶层的声明?

1 个答案:

答案 0 :(得分:0)

我认为这应该有用(在HTML文件下面进行测试)。 查看changeStatus方法(我通过按钮点击进行测试)。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <script type="text/javascript">
      window.ndm = window.ndm || {};
      window.ndm.cam = {'status':'logged-out'};
    </script>

    <script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
    <script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
    <script src="http://foofoo01.com/some.php?login_status=SUBSCRIBER"></script>

    <script>
        function changeStatus(name)
        {
            var scripts = document.getElementsByTagName('script');
            var scriptsToChange = [];
            for (var i = 0; i < scripts.length; i++)
            {
                if (scripts[i].src.indexOf(name) > -1)
                {
                    var oldSrc = scripts[i].src;
                    var newSrc = oldSrc.replace(/(login_status=).*/,'$1' + 'logged-out');
                    scripts[i].setAttribute("src", newSrc);     
                    scriptsToChange.push(scripts[i]);               
                }
            }

            for (var k = 0; k < scriptsToChange.length; k++)
            {
                document.getElementsByTagName("head")[0].appendChild(scriptsToChange[k]);
            }
        }
    </script>
</head>
<body>      
    <button type="button" onclick="changeStatus('foo.com')">Change status</button>
</body>
</html>