Your code has an error. You should not use $('<li>')
, but $('li')
.
When you use $('<li>')
, you are telling jQuery to create a new tag of type li
.
In your case, if you want to work only on items li
within #listagem-simples
, do so:
$(function() {
$('#listagem-simples').find('li').dblclick(function() {
$(this).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="main">
<input type="text" name="novo-item" id="nome-novo-item">
<button id="lista-item">Cadastrar</button>
<ul id="listagem-simples">
<li>Avil</li>
<li>Abocure</li>
<li>Sodral</li>
<li>Ulgran</li>
</ul>
</div>
When you use $('#listagem-simples')
, you are selecting the element with that id
. When you make a find('li')
then you're looking for all li
within that element. So, only the elements in there will get this jQuery function.
Another way to do this would be to use a selector similar to Css3:
$('#lista-simples > li').dblclick(function () {
$(this).remove();
});
// ou ainda
$('#lista-simples li').dblclick(function () {
$(this).remove();
});
In the case of the #lista-simples > li
selector, only the dblclick
function will be executed if the li
element is a child of #lista-simples
. In the second example, #lista-simples li
, any li
that is within #lista-simples
will be affected by dblclick
.
Example:
$(function() {
$('#pega-tudo li').dblclick(function() {
$(this).remove();
});
$('#pega-filhos-imediatos > li').dblclick(function() {
$(this).remove();
});
});
li { cursor:pointer};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulid="pega-tudo">
<h3>todos</h3>
<li>um</li>
<li>dois</li>
<ul>
<li>um</li>
<li>dois</li>
</ul>
</ul>
<ul id="pega-filhos-imediatos">
<h3>imediatos</h3>
<li>um</li>
<li>dois</li>
<ul>
<li>um</li>
<li>dois</li>
</ul>
</ul>
Update
If you're having problems with li
dynamically added within #listagem-simples
, my suggestion is you use on
.
See:
$('#listagem-simples').on('dblclick', 'li', function () {
$(this).remove();
});
Learn more about assigning events to dynamic elements here:
How to bind events to dynamically created elements and pass parameters?