如何使用javascript将标记之间的字符串解析为URL?

时间:2014-07-04 21:02:43

标签: javascript parsing url

如果我的页面上有一个元素:

<a onclick="openUrl();">04-07-2014</a>

如何使用javascript检索内部“04-07-2014”,以便将其附加到URL的末尾? openUrl()必须是什么样的?

2 个答案:

答案 0 :(得分:3)

innerHTML - event.target

的属性访问节点内容

您可以使用event.target获取当前单击的节点并读取它的innerHTML。使用window.location.href = ...;,您将获得与点击链接类似的效果。您还可以使用window.location.replace(..)最接近重定向的内容

<script type="text/javascript">
     function openUrl(e){
            var url = 'www.baseUrl.com/';
            window.location.href = url + e.target.innerHTML;
     }
</script>

...

    <a  href="#" onclick="openUrl(event);">04-07-2014</a>

有关window.location.href = ..window.location.replace(..)检查this article 之间差异的详细信息(我相信有更好的文章可以提供关于......我记得读过很好的一个)

编辑:
我找到了我记得的文章:How to redirect to another webpage in JavaScript/jQuery?

答案 1 :(得分:2)

一种可能性是提供anchor element an id

<a onclick="openUrl();" id="a1" href="#">04-07-2014</a>

使用document.getElementById function检索openUrl函数中锚元素的文本:

function openUrl(){
    var anchorElement = document.getElementById("a1");
    var url = "http://www.somewhere.net/" + anchorElement.textContent;
    alert(url);
}

可以使用textContent or innerHTML property of a node更简洁地编写openUrl函数(不需要id),在这种情况下是锚元素,可以通过this keyword访问:

<a onclick="openUrl(this.textContent);" href="#">04-07-2014</a>

和函数的代码:

function openUrl(p){
    var url = "http://www.somewhere.net/" + p;
    alert(url);
}

两个示例都输出http://www.somewhere.net/04-07-2014

要导航到新位置,请使用window.location

function openUrl(p){
    var url = "http://www.somewhere.net/" + p;
    window.location = url;
}