I try to assign an onclick-event on list bullets, or rather the images replacing them, vi开发者_如何学Pythona JavaScript (or JQuery). I now how to get that work when the list-item is also clickable, but that is not what I need. The list item itself should get a doubleclick-event.
Assuming we have that list:
<ul id="allUsers" class="userselect">
<li id="group1" class="group">Group 1</li>
<li id="user1-1" class="user">User 1.1</li>
<li id="user1-2" class="user">User 1.2</li>
<li id="group2" class="group">Group 2</li>
<li id="user2-1" class="user">User 2.1</li>
...
</ul>
On doubleclick on one user-list-element that user should be added to another list. That works without problems. But now I want to add the single-click event on the list-bullets to expand and collapse the groups, i.e. hide and show the users of each group when clicking.
With using JQuery for my project it seems that there is no selector for list bullets. So I've tried background-images and -images before the list-item text instead but wasn't able to assign my click event. Furthermore, even if I get one of these solutions to work, I would like it better if the clickable list-bullets would be beneath the doubleclickable area because it leads to problems if click and doubleclick both are assigned on the same element.
Has anyone an idea? Thanks in advance.
I don't think the LI bullets are technically part of the DOM, so you can't assign click events to them.
This means you'll have to replace your UL/LI tags with something like <img class="li" src="bullet.gif" />....<br />
on every line, and assign click events to the images.
In addition mblase75's answer, you can also hide the default bullets with CSS.
ul {
list-style:none;
}
You could also wrap the <li>
content in a span to separate it from the image, letting you handle click events separately.
You can recognize the click on bullet with the event.offsetX
value : it is negative if the bullet is hit.
For me that can be a solution. Here is a pure javascript snippet
function click_li(event) {
if (event.offsetX>=0) {
console.log('click on li.#'+event.target.id);
return;
}
console.log('click on bullet li.#'+event.target.id);
let sibling = event.target.nextElementSibling;
if (sibling && sibling.tagName == 'UL')
sibling.classList.toggle('hideUL');
}
.hideUL {
display: none !important;
}
<ul>
<li id="myid1" onclick="click_li(event)">one thing</li>
<ul>
<li>sub list item1</li>
<li>sub list item2</li>
</ul>
<li id="myid2" onclick="click_li(event)">another thing</li>
<ul>
<li>sub list item1</li>
<li>sub list item2</li>
</ul>
</ul>
精彩评论