Tiago Sousa
Tiago Sousa

Reputation: 138

How do I create a <p> tag dynamically and assign it to a var when I click it?

How do I create a <p> tag dynamically and assign it to a var when I click it, it should go to a function goTo and know in what <p> I clicked, in order to access the index of the array lastGoals.

And I have other problem, it is 30 in "30s" I do this function to update and when I click it call the function many times I updated with this function. I know the i is not in the scope of $(document).on(); there is other problem because if I put inside the for it will be addind the click in a bad way I think.

var isFirstTime = true;
var text = '<p class="boxLastGoals">test</p>';
var size = lastGoals.length;
for (var i = 0; i < size; i++) {
   if (isFirstTime) {
   $('#listLastGoals').html(text);
      isFirstTime = false;
    } else {
       $('#listLastGoals').append(text);
    }
}

$(document).on('click', 'p.boxLastGoals', goTo(event, i));

Upvotes: 0

Views: 87

Answers (1)

Will.Harris
Will.Harris

Reputation: 4014

Assuming you are happy using JQuery you can use JQuery to create the <p> element for you inside the loop and attach the click handler dynamically in there. You can also attach the data to the element using the .prop('value', 'test'); method so it can be accessed inside the click handler like $(this).prop('value');.

I've updated my example to include a loop and access a variable to match your scenario

Example

HTML

<div id="content">  
</div>

JavaScript

$(document).ready(function() {
  var list = ['goal 1', 'goal 2', 'goal 3', 'goal 4', 'goal 5'];

  for (var i = 0; i < list.length; i++) {
    var text = list[i];
    var pEl = $('<p></p>', {
      text: text
    });

    pEl.prop('arrayIndex', i);
    pEl.on('click', function(e) {
      goToGoal(e, $(this).prop('arrayIndex'));
    });

    $('#content').append(pEl);
  }
});

function goToGoal(e, i) {
  alert('go to goal: ' + i);
}

JSFiddle to demonstrate

Upvotes: 1

Related Questions