getting inner html of a link when clicked

2019-07-07 12:07发布

I have an HTML Link and a p tag as follows:

<a href="#" onclick="myfun()">Computer Science</a>
<p id="putpara"></p>

This Is My Function :

function myfun() {
            document.getElementById("putpara").innerHTML = this.innerHTML;

        }

However when i click the link the content inside the paragraph tag changes to undefined.

Seems like a silly mistake i am making.....Newbie to javascript....

4条回答
三岁会撩人
2楼-- · 2019-07-07 12:13

this in myfun in your sample, refers to the global object, which in this case would be the Window-object.

You can fix it like this, provided you give your a-tag the ID link:

function myfun() {
    document.getElementById("putpara").innerHTML = document.getElementById("link").innerHTML;
}

If you want to learn more on why you experienced this problem, you should read up on Closures in JavaScript.


EDIT

As pointed out in a comment to my answer, a more reusable solution would be to change the HTML to this:

<a href="#" onclick="myfun(this)">Computer Science</a>

In this case, the onclick-event will be called with the corresponding DOM-element as a parameter.

Then change the JavaScript-function, so that it accepts the passed in element:

function myfun(element) {
    document.getElementById("putpara").innerHTML = element.innerHTML;
}
查看更多
戒情不戒烟
3楼-- · 2019-07-07 12:20

One solution is to send this parameter in your function like this:

html

<a href="#" onclick="myfun(this)">Computer Science</a>
<p id="putpara"></p>

js

window.myfun = function(obj) {
            document.getElementById("putpara").innerHTML = obj.innerHTML;
}

this refers to the DOM element.

fiddle

查看更多
时光不老,我们不散
4楼-- · 2019-07-07 12:29

Do it like this maybe:

function myfun() {
    document.getElementById("putpara").innerHTML = event.target.innerHTML;
}

Or like this(if it's not inside onload or ready function):

window.myfun = function() {
    document.getElementById("putpara").innerHTML = event.target.innerHTML;
}

Explanation:

event.target pretty much returns the object on which the event was dispatched on. According to MDN:

This property of event objects is the object the event was dispatched on. It is different than event.currentTarget when the event handler is called in bubbling or capturing phase of the event.

And:

The event.target property can be used in order to implement event delegation.

Fiddle.

查看更多
劫难
5楼-- · 2019-07-07 12:32

try this :

<a href="#" onclick="myfun(this)">Computer Science</a>
<p id="putpara"></p>

function myfun(obj) {
            document.getElementById("putpara").innerHTML = obj.innerHTML;

        }
查看更多
登录 后发表回答