Javascript add ID to HTML href

折月煮酒 提交于 2021-01-27 07:34:07

问题


I have a livesearch script that i need to populate my html menu with information.

i have a menu how looks something like this:

<a href="?page=page&id=">Menu item</a>

what i'm looking for is a piece of code that would do this to the link:

<a href="?page=page&id=1">Menu item</a>

i have a Javascript that pulls out value ID from a database table (livesearch), now i only need it to get into the href on the fly.

Any suggestions?


回答1:


function addPageIds(){

    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++){
        if (/id=$/.test(links[i].href)) links[i].href += "1";
    }

}



回答2:


<a href="?page=page&id=" id="link1">Menu item</a>

<script type='text/javascript'>
var myidtoinsert = 5;
document.getElementById("link1").href += myidtoinsert;
</script>

Give your a tag an id and then just use document.getElementById to get at the href attribute.



来源:https://stackoverflow.com/questions/1417222/javascript-add-id-to-html-href

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!