Pass the initialized object to javascript function

I have the following initialized object, and I want to pass this object through the onclick function, can this be achieved?

var nameObject = { Name: "Stack", lastName:"Exchange" } 

Here is my code:

In document ready , I have a link with the onclick function, which is added to the html element.

Html:

 <div id="test"></div> 

JavaScript:

 $(document).ready(function () { var nameObject = { Name: "Stack", lastName:"Exchange" }; $("#test").append('<a href="#"' +'onclick="sendObj(**I want to pass "nameObject" into this function)">' +'sendObject</a>'); )}; function sendObj(**receive the object**) { //nameObject.Name+" "nameObject.lastName; } 

Jsfiddle

+4
source share
2 answers

try it

 $(document).ready(function () { var nameObject = { Name: "Stack", lastName:"Exchange" }; $("#test").append('<a href="#" data-caller>sendObject</a>'); $("#test").on("click", "[data-caller]", function() { sendObj(nameObject); }); )}; function sendObj(nameObject) { alert(nameObject.Name+" "+nameObject.lastName); } 

working jsfiddle

+4
source

A more suitable way to do what you want is to store the object in the data element, which is what jQuery stands for.

Then assign a click handler that calls your desired function with the saved data.

 $(document).ready(function () { var name = { Name: "Stack", lastName:"Exchange" }; var a = $('<a href="#">sendObject</a>').data('name', name).on('click', function(e){ sendObj($(this).data('name')); }); $("#test").append(a); }); function sendObj(e) { console.log(e); } 

Demo (welcome console, alert() ditch).

+4
source

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


All Articles