weixin_33721427 2016-11-08 19:16 采纳率: 0%
浏览 32

用空格创建ID

I know that you aren't supposed to create an ID with spaces and that

<div id="id one"></div>

will just create a div with id of id. However a project I am doing using a json file which is set up with a bunch of data, part of the data is the name of the section the user is clicking on to retrieve more data through ajax. However the way it is set up the id for each part on the descriptions.html page needs to match the data in the json file.

I don't want to hyphenate it because having "Build-a-Site" display on my webpage looks just terrible.

We are not supposed to change the ajax or json set up but I'm willing to if there is no other way.

Here is the javascript file that is deciding what is placed on the page, I tried replacing newContent += ('<a href="descriptions.html#'); with newContent += ('<a href="descriptions.html#').replace(/-/g, ""); but that did not remove the hyphens on the page.

// NOTE: This example will not work locally in all browsers. 
// Please try it out on the website for the book http://javascriptbook.com/code/c08/
// or run it on your own server.

$(function() {                                    // When the DOM is ready

  var times;                                      // Declare global variable
  $.ajax({
    beforeSend: function(xhr) {                   // Before requesting data
      if (xhr.overrideMimeType) {                 // If supported
        xhr.overrideMimeType("application/json"); // set MIME to prevent errors
      }
    }
  });

  // FUNCTION THAT COLLECTS DATA FROM THE JSON FILE
  function loadTimetable() {                    // Declare function
    $.getJSON('data/example.json')              // Try to collect JSON data
    .done( function(data){                      // If successful
      times = data;                             // Store it in a variable
    }).fail( function() {                       // If a problem: show message
      $('#event').html('Sorry! We could not load the timetable at the moment');
    });
  }

  loadTimetable();                              // Call the function


  // CLICK ON THE EVENT TO LOAD A TIMETABLE 
  $('#content').on('click', '#event a', function(e) {  // User clicks on event

    e.preventDefault();                                // Prevent loading page
    var loc = this.id.toUpperCase();                   // Get value of id attr

    var newContent = '';                               // Build up timetable by
    for (var i = 0; i < times[loc].length; i++) {      // looping through events
      newContent += '<li><span class="time">' + times[loc][i].time + '</span>';
      newContent += ('<a href="descriptions.html#');
      newContent += times[loc][i].title.replace(/ /g, '-') + '">';
      newContent += times[loc][i].title + '</a></li>';
    }

    $('#sessions').html('<ul>' + newContent + '</ul>'); // Display times on page

    $('#event a.current').removeClass('current');       // Update selected item
    $(this).addClass('current');

    $('#details').text('');                             // Clear third column
  });

  // CLICK ON A SESSION TO LOAD THE DESCRIPTION
  $('#content').on('click', '#sessions li a', function(e) { // Click on session
    e.preventDefault();                                     // Prevent loading
    var fragment = this.href;                               // Title is in href

    fragment = fragment.replace('#', ' #');                 // Add space after#
    $('#details').load(fragment);                           // To load info

    $('#sessions a.current').removeClass('current');        // Update selected
    $(this).addClass('current');
  });


  // CLICK ON PRIMARY NAVIGATION
  $('nav a').on('click', function(e) {                       // Click on nav
    e.preventDefault();                                      // Prevent loading
    var url = this.href;                                     // Get URL to load

    $('nav a.current').removeClass('current');               // Update nav
    $(this).addClass('current');

    $('#container').remove();                                // Remove old part
    $('#content').load(url + ' #container').hide().fadeIn('slow'); // Add new
  });

});

JSON

{
    "L1": [
        {
            "time": "Free",
            "title": "HTML"
        },
        {
            "time": "Free",
            "title": "CSS"
        },
        {
            "time": "$2.99",
            "title": "Build a Site"
        },
        {
            "time": "Free",
            "title": "Javascript"
        },
        {
            "time": "$3.99",
            "title": "Interactive Website"
        },
        {
            "time": "Free",
            "title": "PHP"
        },
        {
            "time": "$4.99",
            "title": "Node.js"
        }
    ],
    "L2": [
       {
            "time": "Free",
            "title": "Python"
        },
        {
            "time": "$2.99",
            "title": "Java"
        },
        {
            "time": "Free",
            "title": "Ruby"
        },
        {
            "time": "$1.99",
            "title": "Ruby on Rails"
        },
        {
            "time": "$2.99",
            "title": "C++"
        },
        {
            "time": "$2.99",
            "title": "C#"
        },
        {
            "time": "$4.99",
            "title": "R"
        }
    ],
    "L3": [
       {
            "time": "Free",
            "title": "SQL"
        },
        {
            "time": "$9.99",
            "title": "Unity 3D"
        },
        {
            "time": "$7.99",
            "title": "Unity 2D"
        },
        {
            "time": "$3.99",
            "title": "AngularJS"
        },
        {
            "time": "$4.99",
            "title": "Django and Flask"
        },
        {
            "time": "$4.99",
            "title": "Visual Java"
        },
        {
            "time": "$7.99",
            "title": "Go"
        }
    ]
}
  • 写回答

1条回答 默认 最新

  • weixin_33728268 2016-11-08 19:33
    关注

    So, you have a json object and want to create links by adding hyphens for the id and using the field as is for the link title.

    You use a regex to replace the space with a hyphen when displaying it, and then leave it alone when using it as the link text.

    To read about regexes (regular expressions): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

    This segment of code replaces the space with a hyphen by using a regex. Adding the g after the clause tells it to replace all instances of it in the string. If you leave the g out it would only replace the first instance.

    sectionOfData[i].title.replace(/ /g, '-')

    **Updated to show OPs edited code:

    var data = {
        "L1": [
            {
                "time": "Free",
                "title": "HTML"
            },
            {
                "time": "Free",
                "title": "CSS"
            },
            {
                "time": "$2.99",
                "title": "Build a Site"
            },
            {
                "time": "Free",
                "title": "Javascript"
            },
            {
                "time": "$3.99",
                "title": "Interactive Website"
            },
            {
                "time": "Free",
                "title": "PHP"
            },
            {
                "time": "$4.99",
                "title": "Node.js"
            }
        ],
        "L2": [
           {
                "time": "Free",
                "title": "Python"
            },
            {
                "time": "$2.99",
                "title": "Java"
            },
            {
                "time": "Free",
                "title": "Ruby"
            },
            {
                "time": "$1.99",
                "title": "Ruby on Rails"
            },
            {
                "time": "$2.99",
                "title": "C++"
            },
            {
                "time": "$2.99",
                "title": "C#"
            },
            {
                "time": "$4.99",
                "title": "R"
            }
        ],
        "L3": [
           {
                "time": "Free",
                "title": "SQL"
            },
            {
                "time": "$9.99",
                "title": "Unity 3D"
            },
            {
                "time": "$7.99",
                "title": "Unity 2D"
            },
            {
                "time": "$3.99",
                "title": "AngularJS"
            },
            {
                "time": "$4.99",
                "title": "Django and Flask"
            },
            {
                "time": "$4.99",
                "title": "Visual Java"
            },
            {
                "time": "$7.99",
                "title": "Go"
            }
        ]
    };
    
    //console.log("Data: ", data["L1"]);
    
    var loc = "L1";
    var sectionOfData = data[loc];
    
    var newContent = '';
    
    for( var i = 0; i < sectionOfData.length; i++ ) {
      var currentItem = sectionOfData[i];
    
      // You can use console.log to debug or help while developing
      //console.log("Building row for item: ", currentItem);
      //console.log("Time: ", currentItem.time);
      
      newContent += '<li><span class="time">' + sectionOfData[i].time + '</span> ';
      newContent += '<a href="descriptions.html#"';
    
      // You are building a link here, so you need to add the id attribute next
      // You want to replace spaces with hyphens for the id.
      newContent += ' id="' + sectionOfData[i].title.replace(/ /g, '-') + '">';
    
      // Next would come your link text, followed by closing tags
      newContent += sectionOfData[i].title + '</a></li>';   
    }
    
    // Replace the contents of the session div with the newContent variable (which are the list items) using jquery
    $('#sessions').html('<ul>' + newContent + '</ul>');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="sessions"></div>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮