Reputation: 1990
if have a jQuery code
var info = $("#info");
for (var i = 0; i < 3; i++) {
$("p").eq(i).on("click", function(event) {
var reply = [
" message=message for first p",
"index = " + $(this).index(),
];
info.append(reply.join(", ") + "<br>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> 0 </p>
<p> 1 </p>
<p> 2 </p>
<div id="info"></div>
here inside the reply array I need to add custom messages for each p
based on the values given as arguments in the function dynamically.How can i achieve it in jquery?I know little that data
attribute can be used but not clear about it.
UPDATE:
I need an object to store the values inside on()
method.
Upvotes: 0
Views: 56
Reputation: 1
Note, for
loop, .eq()
and creating an array to call .join(", ")
on are not necessary.
$("p")
selects all <p>
elements in document
without a filter being applied to selector.
You can concatenate string fragments without creating an array and .join()
.
Call this.tagName
:"P"
as parameter to .index()
, push result to an array defined outside of click
handler.
var info = $("#info");
var arr = [];
var p = $("p").on("click", function(event) {
var index = $(this).index(this.tagName);
var reply = " message=message for first p"
+ ", index = "
+ index
arr.push(index);
info.append(reply + "<br>");
console.log(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> 0 </p>
<p> 1 </p>
<p> 2 </p>
<div id="info"></div>
Upvotes: 0
Reputation: 31692
If you can use data
attribute the just store your message on a data
attribute (like data-message
) and the get it using jQueryElement.attr('data-message')
or jQueryElemenet.data('message')
like this:
var info = $("#info");
for (var i = 0; i < 3; i++) {
$("p").eq(i).on("click", function(event) {
var message = $(this).data("message"); // get the data-message of this p
info.append(message + "<br>"); // use it ...
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-message="hey this is the first"> 0 </p>
<p data-message="and this is 2"> 1 </p>
<p data-message="this will be the THIRD"> 2 </p>
<div id="info"></div>
Upvotes: 2