getting inner html of a link when clicked

◇◆丶佛笑我妖孽 提交于 2020-01-04 02:49:31

问题


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....


回答1:


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




回答2:


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:


try this :

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

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

        }



回答4:


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.



来源:https://stackoverflow.com/questions/24995501/getting-inner-html-of-a-link-when-clicked

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