How to dynamically add function with changing parameters to onclick event?How can I merge properties of two JavaScript objects dynamically?How to change an element's class with JavaScript?Event binding on dynamically created elements?Set a default parameter value for a JavaScript functionHow can I pass a parameter to a setTimeout() callback?How do I attach events to dynamic HTML elements with jQuery?jQuery multiple events to trigger the same functionHow can I add new array elements at the beginning of an array in Javascript?Pass a JavaScript function as parameterHow are parameters sent in an HTTP POST request?

Are these reasonable traits for someone with autism?

Why do airplanes use an axial flow jet engine instead of a more compact centrifugal jet engine?

What was the idiom for something that we take without a doubt?

Looking for a soft substance that doesn't dissolve underwater

What to do when you've set the wrong ISO for your film?

pic versus macro in TikZ

Is the Starlink array really visible from Earth?

Would Brexit have gone ahead by now if Gina Miller had not forced the Government to involve Parliament?

Website returning plaintext password

Why are C64 games inconsistent with which joystick port they use?

In the current era, do any wizards survive from 1372 DR?

How to illustrate the Mean Value theorem?

How strong are Wi-Fi signals?

Make 24 using exactly three 3s

What is quasi-aromaticity?

Is the field of q-series 'dead'?

My employer faked my resume to acquire projects

Line of lights moving in a straight line , with a few following

Where's this lookout in Nova Scotia?

Does the unit of measure matter when you are solving for the diameter of a circumference?

Why aren't space telescopes put in GEO?

Installed Electric Tankless Water Heater - Internet loss when active

Simple fuzz pedal using breadboard

Employer asking for online access to bank account - Is this a scam?



How to dynamically add function with changing parameters to onclick event?


How can I merge properties of two JavaScript objects dynamically?How to change an element's class with JavaScript?Event binding on dynamically created elements?Set a default parameter value for a JavaScript functionHow can I pass a parameter to a setTimeout() callback?How do I attach events to dynamic HTML elements with jQuery?jQuery multiple events to trigger the same functionHow can I add new array elements at the beginning of an array in Javascript?Pass a JavaScript function as parameterHow are parameters sent in an HTTP POST request?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm adding an onlick event dynamically to a series of anchor elements. For each anchor element I need to use different parameter values, in the form of variables. when using the following event listener in a loop:



anchor.addEventListener("click", () => task(title, author) );


title and author for every anchor element's onclick end up the same (they are all the value of title and author at their last iteration). I'd like them to represent the values of the variables at the particular iteration in the loop. Here's a minimal working code example:



for (obj of objTasks) 
title = obj.title;
author = obj.author;

var anchor = document.createElement("a");

anchor.addEventListener("click", () => task(title, author) );










share|improve this question



















  • 4





    I wouldn't use global variables like that, because it won't work as expected ... declare for(let obj and const title = and const author = and you'll find the code works

    – Jaromanda X
    Mar 24 at 5:31











  • What is the issue you're having? It seems like you already solved your problem?

    – ChrisBrownie55
    Mar 24 at 5:32

















0















I'm adding an onlick event dynamically to a series of anchor elements. For each anchor element I need to use different parameter values, in the form of variables. when using the following event listener in a loop:



anchor.addEventListener("click", () => task(title, author) );


title and author for every anchor element's onclick end up the same (they are all the value of title and author at their last iteration). I'd like them to represent the values of the variables at the particular iteration in the loop. Here's a minimal working code example:



for (obj of objTasks) 
title = obj.title;
author = obj.author;

var anchor = document.createElement("a");

anchor.addEventListener("click", () => task(title, author) );










share|improve this question



















  • 4





    I wouldn't use global variables like that, because it won't work as expected ... declare for(let obj and const title = and const author = and you'll find the code works

    – Jaromanda X
    Mar 24 at 5:31











  • What is the issue you're having? It seems like you already solved your problem?

    – ChrisBrownie55
    Mar 24 at 5:32













0












0








0








I'm adding an onlick event dynamically to a series of anchor elements. For each anchor element I need to use different parameter values, in the form of variables. when using the following event listener in a loop:



anchor.addEventListener("click", () => task(title, author) );


title and author for every anchor element's onclick end up the same (they are all the value of title and author at their last iteration). I'd like them to represent the values of the variables at the particular iteration in the loop. Here's a minimal working code example:



for (obj of objTasks) 
title = obj.title;
author = obj.author;

var anchor = document.createElement("a");

anchor.addEventListener("click", () => task(title, author) );










share|improve this question
















I'm adding an onlick event dynamically to a series of anchor elements. For each anchor element I need to use different parameter values, in the form of variables. when using the following event listener in a loop:



anchor.addEventListener("click", () => task(title, author) );


title and author for every anchor element's onclick end up the same (they are all the value of title and author at their last iteration). I'd like them to represent the values of the variables at the particular iteration in the loop. Here's a minimal working code example:



for (obj of objTasks) 
title = obj.title;
author = obj.author;

var anchor = document.createElement("a");

anchor.addEventListener("click", () => task(title, author) );







javascript events parameters






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 5:40







erv

















asked Mar 24 at 5:30









erverv

315215




315215







  • 4





    I wouldn't use global variables like that, because it won't work as expected ... declare for(let obj and const title = and const author = and you'll find the code works

    – Jaromanda X
    Mar 24 at 5:31











  • What is the issue you're having? It seems like you already solved your problem?

    – ChrisBrownie55
    Mar 24 at 5:32












  • 4





    I wouldn't use global variables like that, because it won't work as expected ... declare for(let obj and const title = and const author = and you'll find the code works

    – Jaromanda X
    Mar 24 at 5:31











  • What is the issue you're having? It seems like you already solved your problem?

    – ChrisBrownie55
    Mar 24 at 5:32







4




4





I wouldn't use global variables like that, because it won't work as expected ... declare for(let obj and const title = and const author = and you'll find the code works

– Jaromanda X
Mar 24 at 5:31





I wouldn't use global variables like that, because it won't work as expected ... declare for(let obj and const title = and const author = and you'll find the code works

– Jaromanda X
Mar 24 at 5:31













What is the issue you're having? It seems like you already solved your problem?

– ChrisBrownie55
Mar 24 at 5:32





What is the issue you're having? It seems like you already solved your problem?

– ChrisBrownie55
Mar 24 at 5:32












1 Answer
1






active

oldest

votes


















0














You're declaring your variables globally - use let because it's block-scoped (var is function scoped):



for (let obj of objTasks) 
let title = obj.title;
let author = obj.author;
let anchor = document.createElement("a");
anchor.addEventListener("click", () => task(title, author) );






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320995%2fhow-to-dynamically-add-function-with-changing-parameters-to-onclick-event%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You're declaring your variables globally - use let because it's block-scoped (var is function scoped):



    for (let obj of objTasks) 
    let title = obj.title;
    let author = obj.author;
    let anchor = document.createElement("a");
    anchor.addEventListener("click", () => task(title, author) );






    share|improve this answer



























      0














      You're declaring your variables globally - use let because it's block-scoped (var is function scoped):



      for (let obj of objTasks) 
      let title = obj.title;
      let author = obj.author;
      let anchor = document.createElement("a");
      anchor.addEventListener("click", () => task(title, author) );






      share|improve this answer

























        0












        0








        0







        You're declaring your variables globally - use let because it's block-scoped (var is function scoped):



        for (let obj of objTasks) 
        let title = obj.title;
        let author = obj.author;
        let anchor = document.createElement("a");
        anchor.addEventListener("click", () => task(title, author) );






        share|improve this answer













        You're declaring your variables globally - use let because it's block-scoped (var is function scoped):



        for (let obj of objTasks) 
        let title = obj.title;
        let author = obj.author;
        let anchor = document.createElement("a");
        anchor.addEventListener("click", () => task(title, author) );







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 24 at 5:50









        Jack BashfordJack Bashford

        22.4k52051




        22.4k52051





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320995%2fhow-to-dynamically-add-function-with-changing-parameters-to-onclick-event%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해