简体   繁体   中英

looking for a more efficient way to write this jquery

This code works as is but I'm looking for a more efficient way to write this jquery code. The goal of the code, when a show is selected(clicked) the display div will display show details when the next show is clicked it replace the details of the previously selected show in the display div.

enter code here

/*jslint browser: true*/
/*global $, jQuery, alert*/
$(document).ready(function () {
    "use strict"; 
    $('#shows_morning_news').click(function () {
    $('#shows_info_display').html($('#display_morning_news').html());
    });
    $('#shows_danielle_smith').click(function () {
    $('#shows_info_display').html($('#display_danielle_smith').html());
    });
    $('#shows_rob_breakenridge').click(function () {
    $('#shows_info_display').html($('#display_rob_breakenridge').html());
    });
    $('#shows_calgary_today').click(function () {
    $('#shows_info_display').html($('#display_calgary_today').html());
    });
    $('#shows_sports_talk').click(function () {
    $('#shows_info_display').html($('#display_sports_talk').html());
    });
    $('#shows_charles_adler').click(function () {
    $('#shows_info_display').html($('#display_charles_adler').html());
    });
});

You could try this:

/*jslint browser: true*/
/*global $, jQuery, alert*/
$(document).ready(function() {
  "use strict";
  [
    "morning_news",
    "danielle_smith",
    "rob_breakenridge",
    "calgary_today",
    "sports_talk",
    "charles_adler"
  ].map(function(id) {
    $("#shows_" + id).click(function() {
      $("#shows_info_display").html($("#display_" + id).html());
    });
  });
});

CodePen Demo

You may use you current id value to achieve it. Check the below code.

$(document).on("click",function(){
    var id = $(this).attr("id");
    if(id.search("shows") == 0){
        var requiredIdPart = id.replace("shows","");
        $("#shows_info_display").html($("#display"+requiredIdPart).html());
    }
});

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