简体   繁体   English

设置onclick <a>使用javascript</a>

[英]Set onclick of <a> using javascript

I want to change all the links in a div such that they no longer refer to a page, but run a javascript function when being clicked. 我想更改div中的所有链接,以便它们不再引用页面,但在单击时运行javascript函数。 To do so, I wrote this function: 为此,我写了这个函数:

function buildPageInDiv(htmlString){
    console.log(typeof htmlString);
    $div = $(htmlString).children("div#myDiv");
    $div.children("a").each(function(i, element){toJavascriptLinks(element)});
    document.getElementById("targetDiv").innerHTML = $div[0].innerHTML;
}

calling this function: 调用此函数:

function toJavascriptLinks(element){
    element.href="#";
    element.onclick     = function(){console.log('Yeah!')};
    console.log(element);
}

Now, when I run 'buildPageInDiv', 'string' is printed on the console, all the "href" are changed to "#" and for every within the div the console prints the element: 现在,当我运行'buildPageInDiv'时,在控制台上打印'string',所有“href”都变为“#”,而对于div中的每一个,控制台都会打印元素:

 <a href="#">

No sign of the onclick here, and clicking on the link does not show anything on the console. 这里没有onclick的迹象,点击链接在控制台上没有显示任何内容。

What am I missing here? 我在这里错过了什么?

Edit: 编辑:

I was seeking in the wrong place. 我在错误的地方寻找。 The problem was that I was running 'toJavascriptLinks(element)' before attaching the innerHTML to 'targetDiv'. 问题是我在将innerHTML附加到'targetDiv'之前运行'toJavascriptLinks(element)'。 That was no problem for the href attribute, but it was for the onclick attribute. 这对于href属性来说没有问题,但它适用于onclick属性。 Solution is simply to put it in 'targetDiv' first and than run 'toJavascriptLinks(element)' on 'targetDiv' : 解决方案只是先将它放在'targetDiv'中,然后在'targetDiv'上运行'toJavascriptLinks(element)':

function buildPageInDiv(htmlString){
    console.log(typeof htmlString);
    var content = $(htmlString).children("div#myDiv")[0].innerHTML;
    document.getElementById("targetDiv").innerHTML = content;
    $("div#targetDiv").children("a").each(function(i, element) toJavascriptLinks(element)});
}

Although the problem was not in the code I originally posted, the comprehensive answers below led me to the solution. 虽然问题不在我最初发布的代码中,但下面的综合答案使我得到了解决方案。

First: All type of selectors in jQuery, start with the dollar sign and parentheses: $() 第一:jQuery中所有类型的选择器,以美元符号和括号开头:$()
Secondly: you need to close your statements with ; 其次:你需要关闭你的陈述;
Lastly: it is good practice to define your functions BEFORE you call them, instead of relying on javascript to hoist them to the top for you. 最后:在您调用函数之前定义函数是一种很好的做法,而不是依靠javascript将它们提升到最顶层。 This will also make jslint validate, whereas the other way round wouldn't! 这也将使jslint验证,而反过来不会!

So your code without your errors would look like: 所以没有错误的代码看起来像:

function toJavascriptLinks(element){
    element.href="#";
    element.onclick     = function(){alert('Yeah!');};
    console.log(element);
}

$('div').children("a").each(function(i, element){toJavascriptLinks(element);});

See this fiddle for a working demo. 一下工作演示的小提琴

Good Luck!! 祝好运!!


ABOUT YOUR UPDATED QUESTION: 关于你的更新问题:
That's quite an update to your question. 这是你的问题的一个更新。

You don't see your onclick in console.log because you set the onclick event in the dom. 您没有在console.log中看到您的onclick,因为您在dom中设置了onclick事件。 If you wanted to see the onclick in console.log, you would add the function STRING using: 如果你想在console.log中看到onclick,你可以使用以下命令添加STRING函数:
element.setAttribute('onclick', 'your function string');

Suppose in your html you have: 假设你的html中有:

<a id="link_a" href="http://www.google.com">link 1</a>
<a id="link_b" href="http://www.duckduckgo.com">link 2</a>

And you have this javascript: 你有这个javascript:

var lnkA=document.getElementById("link_a");
var lnkB=document.getElementById("link_b");

lnkA.onclick=function(){alert(this.innerHTML);};
lnkB.setAttribute('onclick','alert(this.innerHTML);');

console.log(lnkA.outerHTML);
console.log(lnkB.outerHTML);

Then console.log will contain: 然后console.log将包含:

<a id="link_a" href="http://www.google.com">link 1</a>
<a onclick="alert(this.innerHTML);" id="link_b" href="http://www.duckduckgo.com">link 2</a>

See this fiddle for a live example of this explanation. 请参阅此小提琴 ,了解此解释的实例。

I also think you are already using some form of jQuery (without you knowing it) because of your use of .children("div#myDiv") . 我也认为你已经在使用某种形式的jQuery(不知道它),因为你使用了.children("div#myDiv") To my knowledge this no plain vanilla javascript. 据我所知,这不是简单的香草javascript。 And I think both plain vanilla javascript and jQuery would not select those divs with id 'myDiv' out of a plain html-string, so the code in your update would not do the job. 我认为简单的vanilla javascript和jQuery都不会从普通的html字符串中选择id为'myDiv'的div,因此更新中的代码无法完成这项工作。

Finally, to adjust my answer to your updated question and expectation of the onclick-event being visible in the parsed html-source: 最后,调整我对更新问题的答案,并期望onclick-event在解析后的html源中可见:

var htmlString='<div id="myDiv"><a href="http://www.google.com">link 1</a><a href="http://www.duckduckgo.com">link 2</a></div><div id="otherDiv"><a href="http://www.asdf.com">link 3</a><a href="http://www.yahoo.com">link 4</a></div>';

function toJavascriptLinks(element){
    element.href="#";
    element.setAttribute('onclick','console.log("Yeah!");');
    console.log(element.outerHTML);
}

//no innerHTML on documentFragment allowed, yet on it's children it's allowed
var frag = document.createDocumentFragment().appendChild( document.createElement('div') );
frag.innerHTML=htmlString;

var $div = $(frag).children('div#myDiv');

$($div).children("a").each(function(i, element){toJavascriptLinks(element);});


var outp=document.getElementById("output");
outp.innerHTML=frag.innerHTML;

See this updated fiddle to see it in action. 看到这个更新的小提琴 ,看看它在行动。

That leaves the question: why on earth are you placing 'ninja' $-signs front of your variable names? 这就留下了一个问题:为什么你在变量名前面放置'ninja'$ -signs?

That's just the way the debugger displays an HTML element. 这就是调试器显示HTML元素的方式。 It doesn't show all attributes - especially since you are setting the DOM property onclick to a function reference, which can't be displayed as the HTML attribute onclick which takes a string ( 它没有显示所有属性 - 特别是因为您将DOM 属性设置为onclick一个函数引用,该函数引用无法显示为带有字符串的HTML 属性 onclick which AFAIK can't be set with JavaScript 哪个AFAIK无法使用JavaScript设置 see Luc's comment). 见吕克的评论)。

Try console.log(element.onclick); 试试console.log(element.onclick); instead, it should display something like function() {...} . 相反,它应该显示类似function() {...}

Or doesn't the event handle work? 或者事件处理不起作用?

BTW, any reason you don't use jQuery to set the href and the handler? 顺便说一句,你不使用jQuery设置href和处理程序的任何原因?

$div.children("a").attr('href', '#').click(function(){console.log('Yeah!')});

One more thing: In most consoles you can click on <a href="#"> and it will display the DOM properties, which should include the event handler. 还有一件事:在大多数控制台中,您可以单击<a href="#"> ,它将显示DOM属性,其中应包括事件处理程序。

I would really use jQuery for this, it's quite simple. 我真的会使用jQuery ,这很简单。

​$(function() {
    $("div > a ").attr("href", "#").click(function(e) {
        e.preventDefault();
        doSomething();
    });
});

var doSomething = function() {
    alert("Woah, it works!");
}

See the following jsfiddle for it in action: http://jsfiddle.net/SsXtt/1/ 请参阅以下jsfiddle: http//jsfiddle.net/SsXtt/1/

Are you sure the element is correct? 你确定元素是否正确? This works for me. 这适合我。

<a id="mylink">Test</a>
<script>
    document.getElementById("mylink").onclick = function() {
        alert("Works");
    };
</script>

函数需要在字符串中,尝试添加引号?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM