Angular Angular - 4 months ago 17
jQuery Question

Jquery get id of list elements and call function based on click

Based on the click of the list elements ( whose ids I set to be the same as the objects), I want to call a function ( in this case, just print that object). I don't want to attach an onclick to every list item. I want something like this.

$('#li.menu').click(function(){
$('li').each(function(){
var id= $(this).attr('id');
}
//when the id is clicked, see the object and if it's there and call print on it)
});



//sample function:

function print(x){
console.log(x);
}

Var myObject = {
obj1:{ JSON here},
obj2:{ JSON here }
}





<!-- Bootstrap Simple Sidebar: Sidebar -->
<div id="sidebar-wrapper">
<ul class="sidebar-nav" id="menu">
<li>
<a id="obj1" href="#repo">Repository </a>
</li>
<li>
<a id="obj2" href="#config">Configuration</a>
</li>

</ul>
</div>

Answer

Event delegation, using the correct selector, brackets syntax, and correct capitalization do it:

// It's `var`, not `Var` -- capitalization matters in JavaScript
var myObject = {          
    obj1: { foo: "I'm obj1" },
    obj2: { foo: "I'm obj2" }
};

// Event delegation: Hook click on #menu, only fire handler if
// the click goes through an `a` element
$('#menu').on("click", "a", function(){
    //             vvvvvvv-- id of the clicked element
    print(myObject[this.id]);
    // Brackets --^-------^
});
function print(x){
    console.log(x);
}
<div id="sidebar-wrapper">
    <ul class="sidebar-nav" id="menu">
        <li>
            <a id="obj1" href="#repo">Repository </a>
        </li>
        <li>
            <a id="obj2" href="#config">Configuration</a>
        </li>

    </ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>