最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calling jQuery function after click on some element - Stack Overflow

programmeradmin3浏览0评论

Here is the HTML code:

<p onclick='javascript:func(this);'>Bla bla bla</p>

and here is the script (it is written in the head of the document):

function func(e) {
  var t = e.text();
  console.log(t);
}

It doesn't work and I don't understand why. The error message is:

"Object # has no method 'text'".

Here is the HTML code:

<p onclick='javascript:func(this);'>Bla bla bla</p>

and here is the script (it is written in the head of the document):

function func(e) {
  var t = e.text();
  console.log(t);
}

It doesn't work and I don't understand why. The error message is:

"Object # has no method 'text'".

Share Improve this question edited Jul 17, 2022 at 22:11 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 5, 2013 at 6:44 enjakuenjaku 3464 silver badges18 bronze badges 1
  • I don't see any jQuery. – Felix Kling Commented Jul 5, 2013 at 6:59
Add a ment  | 

6 Answers 6

Reset to default 5

Wrap it in the jQuery wrapper. .text() is a jQuery method, and your element e is a plain Javascript DOM element, so you need the jQuery wrapper.

var t = $(e).text();

Side note: unobtrusive event handler assignments are preferred to inline handlers. For example:

$(document).ready(function(){
    $('p').click(function(){
        var t = $(this).text();
        console.log(t);
    });
});

The above uses jQuery to assign the click handler (instead of inline Javascript) and so because of that, the element can be accessed in this for the plain Javascript object, or $(this) for the jQuery object.

Fiddle

This is plain javascript and will do what you ask for.

function func(e) {
  var t = e.innerHTML;
  console.log(t);
}

Use innerText if you do not use jquery.

function func(e) {
  var t = e.innerText;
  console.log(t);
}

Right way is:

HTML:

<p onclick='func(this);'>Bla bla bla</p>

instead of

<p onclick='javascript:func(this);'>Bla bla bla</p>

Javascript:

function func(e) {
    var t = e.innerHTML;
    console.log(t);
}

Jquery is designed to be unobtrusive. If your adding onclick attributes everywhere your doing it wrong.

Instead you should be adding event listeners

<p>Blah Blah Blah</p>

Jquery/Script

$(document).ready(function(){
    $('p').on('click', function(){
        console.log($(this).text());
    });
});

Try using innerHTML:

function func(e) {
    var t= e.innerHTML;
    console.log(t);
}
发布评论

评论列表(0)

  1. 暂无评论