"a" element in JavaScript

"a" element in JavaScript

本文关键字:quot JavaScript in element      更新时间:2023-09-26

我需要一个函数,将代码放在HTML"a"元素中。我尝试过下面发布的代码的许多不同变体,但都没有成功。

    var doc = document.body;
    function h1(text) {
        var h1 = document.createElement("h1");
        var t = document.createTextNode(text);
        h1.appendChild(t);
        doc.appendChild(h1);
    }
    function a(a, b) {
        var doc1 = document.createElement("a");
        doc.a;
        var s;
        s = document.createElement('script');
        s.innerHTML = b;
        doc.appendChild(doc1);
        doc = doc1;
        doc1.appendChild(s);
        doc = document.body;
    }
    a("href=www.google.com", "h1('"hello'");");

http://jsfiddle.net/huzuno93/

我很好奇你是如何完成这一特定尝试的,但以下是你如何正确地完成这一尝试的(至少我认为这是你想要做的):

var doc = document.body;
function h1(text) {
  var h1 = document.createElement("h1");
  var t = document.createTextNode(text);
  h1.appendChild(t);
  return h1;
}
function a(a, b) {
  var link = document.createElement("a");
  link.href = a;
  link.appendChild(b);
  return link;
}
doc.appendChild(a("http://www.google.com", h1("hello")));
doc.appendChild(h1("wazzap"));

一般来说,我建议不要使用参数或变量与其同名的函数。这让它非常令人困惑。

谢谢@JLRishe你的回答真的帮我解决了这个问题。之后,审查你的代码,编辑我的代码,并在互联网上寻找我能找到的解决方案。

    function h1(text) {
        base = document.createElement("h1");
        var t = document.createTextNode(text);
        base.appendChild(t);
        doc.appendChild(base);
    }
    function a() {
        doc1 = document.createElement("a");
        doc.appendChild(doc1);
        doc1.appendChild(base);
    }
    function href(a) {
        doc1.href = a;
    }
    a(h1("hello"));
    href("www.google.com");
    h1("hello");

http://jsfiddle.net/7ju91jpm/

它在JSFiddle中对我不起作用,但它在我需要的地方起作用。