0

我正在尝试用 javascript 替换 html 元素属性的值。我很确定我以前见过它,但我不确定语法在这些事情上是如何工作的。例子:

<a href="javascript:bookmarksite('Website Name', "<script type="text/javascript">document.write(location.href);
</script>')">Click Here to Bookmark this Page</a>
4

2 回答 2

2

你可以这样做:HTML:

<a id="link" href="#">Click me</a>

JavaScript:

document.getElementById("link").setAttribute("href", "page.html");
于 2013-03-21T17:30:42.540 回答
0

不显眼的 JavaScript 总是处理这些事情的好方法:

(function(d){
    var modern = function(){
        return(d.addEventListener);
    }, event = function(obj, evt, fn){
        if(modern()) {
            obj.addEventListener(evt, fn, false);
        } else {
            obj.attachEvent("on" + evt, fn);
        }
    }, load = function(fn){
        if(modern()) {
            d.addEventListener("DOMContentLoaded", function go(){
                d.removeEventListener("DOMContentLoaded", go, false);
                fn();
            }, false);
        } else {
            d.attachEvent("onreadystatechange", function go(){
                if(d.readyState === "complete") {
                    d.detachEvent("onreadystatechange", build);
                    fn();
                }
            });
        }
    }, init = function(){
        var link = d.getElementById("bookmark_link");
        event(link, "click", function(e){
            bookmarksite("Website Name", location.href);
            // Set attribute(s) here
            link.setAttribute("href", "whatever_you_want.html");
        });
    };
    load(init);
})(document);

然后在链接中:

<a href="#" id="bookmark_link">Bookmark this page</a>
于 2013-03-21T17:50:01.903 回答