简体   繁体   中英

PHP and Javascript. Code optimization

I would like some help to optimize my code.

I have a product list.

<ul>
  <li><a href="#" id="item1"> Item 1 </a></li>
  <li><a href="#" id="item2"> Item 2 </a></li>
</ul>

For every item I have a section with the item's details.

<div id="item1-details"> Item Details 1 </div>
<div id="item2-details"> Item Details 2 </div>

These sections are hidden. They only appear when the user clicks on the item listed above.

$("#item1").click(function() { $("#item1-details").show(); });
$("#item2").click(function() { $("#item2-details").show(); });

Up to this point I have no problems. The logic is very basic. The problem comes when the information is retrieved from the database.

I have two blocks. 块。 One to populate the - ul - list and another to create the detail's sections. I can use the item ID to make unique the link and use the same ID adding a character to make unique the details section. But how can I create this automatism with jQuery.

I hope I was clear, even with my English. Thank you all.

you can use data attributes like this

<li><a href="#" id="item1" data-id="1"> Item 1 </a></li>

and then

$("#item1").click(function() { 
    $attr = $(this).attr('data-id');
    $("#item"+$attr+"-details").show(); 
});

Based on the fact that the ids are related, you can just use simple click, grab the id, and show it.

$("li").on("click", "a", function(evt) {  //detect click on anchors in the li
    var id = this.id;                  //get id of what is clicked
    $("#" + id + "-details").show();   //show the element 
    evt.preventDefault();
});

You could do, get the id and with cointains (*=) show the the div :

$('div').hide();
$('ul a').click(function(){
    $('div[id*=' + this.id +']').toggle();
    })

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM