简体   繁体   中英

get text from an link with onclick in javascript

how to get text from an link with onclick ?

my code :

<a href='#' onclick='clickfunc()'>link</a>

 function clickfunc() {
        var t = text();
        alert(t);
    }

text = link

try this

 <a href='#' onclick='clickfunc(this)'>link</a>

 function clickfunc(obj) {
    var t = $(obj).text();
    alert(t);
 }

well, it is always better and recommended to avoid inline javascript( onclick() ).. rather you can use

$('a').click(function(){
    alert($(this).text());
});

or to be more specific...give an id to <a> and use id selector

 <a href='#' id='someId'>link</a>

 $('#someId').click(function(){
    alert($(this).text());
});
<a href='#' onclick='clickfunc(this)'>link</a>

clickfunc = function(link) {
  var t = link.innerText || link.textContent;
  alert(t);
}

JSFiddle Demo

try this with pure javascript

<a href='#' onclick='clickfunc(this)'>link</a>

 function clickfunc(this) {
    var t = this.innerText;
    alert(t);
}

You can do this:

HTML

<a href='#' onclick='clickfunc(this)'>link</a>

JS

function clickfunc(obj) {
    var t = $(obj).text();
    alert(t);
}

Demo: Fiddle

With jQuery you can do it this way.

$(document).on('click', 'a', function(event){
    event.preventDefault();

    alert($(this).text);
});

html

<a href='#' id="mylink" onclick='clickfunc()'>link</a>

js

function clickfunc() {
            var l = document.getElementById('mylink').href; //for link
            var t = document.getElementById('mylink').innerHTML; //for innerhtml
            alert(l);
            alert(t);
        }

Try this easy using jQuery

$('a').click(function(e) {
  var txt = $(e.target).text();
  alert(txt);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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