javascript 在javascript中使用onclick从链接中获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19633201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:15:57  来源:igfitidea点击:

get text from an link with onclick in javascript

javascriptjquery

提问by john

how to get text from an link with onclick ?

如何使用 onclick 从链接中获取文本?

my code :

我的代码:

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

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

text = link

文字 =链接

回答by bipen

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

好吧,它总是更好,建议避免内联 javascript( onclick()).. 而你可以使用

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

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

或者更具体地说......给一个id<a>并使用id选择器

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

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

回答by Alexander Presber

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

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

JSFiddle Demo

JSFiddle 演示

回答by Nauphal

try this with pure javascript

用纯 javascript 试试这个

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

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

回答by pala?н

You can do this:

你可以这样做:

HTML

HTML

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

JS

JS

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

Demo: Fiddle

演示:小提琴

回答by Bernhard

With jQuery you can do it this way.

使用 jQuery,您可以这样做。

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

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

回答by Vijay Verma

html

html

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

js

js

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

回答by kbvishnu

Try this easy using jQuery

使用 jQuery 试试这个简单的方法

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