使用空格创建ID

时间:2016-11-08 19:16:58

标签: javascript html json ajax

我知道你不应该用空格创建一个ID

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

只会创建一个ID为id的div。 但是我正在使用json文件创建一个项目,该文件设置有一堆数据,部分数据是用户点击以通过ajax检索更多数据的部分的名称。但是,设置descriptions.html页面上每个部分的id的方式需要与json文件中的数据匹配。

我不想连字,因为有#34; Build-a-Site&#34;在我的网页上显示看起来很糟糕。

我们不应该改变ajax或json设置,但如果没有别的办法,我愿意。

以下是决定页面上放置内容的javascript文件,我尝试将newContent += ('<a href="descriptions.html#');替换为newContent += ('<a href="descriptions.html#').replace(/-/g, "");,但未删除页面上的连字符。

// 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 个答案:

答案 0 :(得分:5)

因此,您有一个json对象,并希望通过为id添加连字符并使用该字段作为链接标题来创建链接。

使用正则表达式在显示时用连字符替换空格,然后在将其用作链接文本时不管它。

阅读有关正则表达式(正则表达式)的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

这段代码使用正则表达式用连字符替换空格。在子句之后添加g告诉它替换字符串中的所有实例。如果你把它留下来它只会取代第一个实例。

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

**更新以显示OP编辑的代码:

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>