Call jQuery function after clicking on any element

Here is the HTML code

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

and here is the script (it is written at the beginning of the document).

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

This does not work, and I do not understand why. Error message: "Object no. Has no text text method."

+4
source share
6 answers

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

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

Side note: unobtrusive event handler assignments are preferable to built-in handlers. For instance:

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

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

+5
source

Fiddle

This is simple javascript and will do what you ask.

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

Try using innerHTML :

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

Use innerText if you are not using jquery.

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

The right way:

HTML:

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

instead

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

JavaScript:

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

Jquery is designed for unobtrusiveness. If you add onclick attributes everywhere that you do it wrong.

Instead, you should add event listeners

 <p>Blah Blah Blah</p> 

Jquery / script

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

Source: https://habr.com/ru/post/1489850/


All Articles