Reputation: 29514
I have created a Div Tag inside menu li
and added a Class Div1
to it.
Everything working good.
But Now I want to create div tags with div1
, and on another click div2
and then div3
.
So is it possible to use variable and have a counter inside it?
$(document).ready(function() {
$(".menu a").click(function() {
$("<div> Label </div>").appendTo(".menu li").addClass("div1");
$(".div1").show(function() {
$(".div1").editInPlace({
url: "./server",
show_buttons: true
}); //editinplace
}); //show
}); //click
});
Upvotes: -1
Views: 921
Reputation: 48751
Without your source HTML, or expected HTML it is difficult to know what you are trying to accomplish.
If you want a jQuery listener, I would advise you use $.fn.on
and use the this
reference to get the context of the event.
Note: I added a convenience jQuery plugin called $.fn.incrementAndGet
to increment a data value and return its new value. This is a simple way to store a counter in the DOM.
(function($) {
$.fn.editInPlace = function({ url, show_buttons }) {
console.log('EDIT', { class: $(this).prop('class'), url, show_buttons });
};
$.fn.incrementAndGet = function(key, amount) {
const newValue = this.data(key) + amount;
this.data(key, newValue);
return newValue;
};
})(jQuery);
$(() => {
$('.menu').data('count', 0).on('click', 'a', function() {
const $a = $(this);
const $li = $a.closest('li');
const $menu = $li.closest('.menu');
const count = $menu.incrementAndGet('count', 1);
const className = `div-${count}`;
$li.append($('<div>', { text: `Label-${count}`, class: className }));
$(`.${className}`).show(function() {
$(this).editInPlace({
url: "./server",
show_buttons: true
});
});
});
});
.as-console-wrapper { max-height: 5rem !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<nav class="menu">
<ul>
<li><a href="#">News</a></li>
<li><a href="#">Archive</a></li>
<li><a href="#">Videos</a></li>
</ul>
</nav>
Upvotes: 0
Reputation: 40512
I think you don't need to specify div1,div2 etc. I've used edit in place with jquery. I just add same class (like editable) to all the elements that I need to edit in place and put in ready function like this:
$(document).ready(function(){
$(".editable").editInPlace(...../*other stuff*/);
});
Upvotes: -1
Reputation: 9275
Not sure why you want to change the class, but in case you do that's included... i don't see the ID getting set....
$(document).ready(function()
{
var increment = 0;
$(".menu a").click(function ()
{
increment++;
$("<div> Label </div>").appendTo(".menu li").addClass("div" + increment);
$(".div" + increment).show(function ()
{
$(".div" + increment).editInPlace({
url: "./server",
show_buttons: true
});//editinplace
});//show
});//click
});
the scope chaining in javascript means that the 'increment' variable is always visible to the click function.
Upvotes: 0