【问题标题】:How do I change or update <p> tag data with every client request如何使用每个客户端请求更改或更新 <p> 标记数据
【发布时间】:2021-08-23 23:41:22
【问题描述】:

这是我的代码,

if(data.country_name == 'India'){
        $('.fact').append("<h2 id='india'>Fact about India</h2>");
    $('.fact').append("<p>The world's highest cricket ground is in Chail, Himachal Pradesh. Built in 1893 after leveling a hilltop, this cricket pitch is 2444 meters above sea level.</p>");
$(.fact).append('<p>2</p>')
$(.fact).append('<p>3</p>')
$(.fact).append('<p>4</p>')
    console.log('this a india');
    } else if(data.country_name == 'Turkey'){
        $('.fact').append("<h2 id='turkey'>Fact about Turkey</h2>");
        $('.fact').append('<p>The story of Santa Claus originated in Turkey</p>');
    }else if(data.country_name == 'Russia'){
        $('.fact').append("<h2 id='russia'>Fact about Russia</h2>");
        $('.fact').append('<p>Russia is home to some 20 percent of the world’s trees, and one-fifth of the world’s freshwater is in Lake Baikal.</p>');
    }

现在,如果我在 class='fact' 中为印度的事实添加 4 个&lt;p&gt;,那么只要客户位置是印度,它就需要从 if 语句中随机显示 1 个&lt;p&gt;

任何人都可以帮忙,我把它弄复杂了,我知道它可能太简单了!!

【问题讨论】:

    标签: javascript html jquery web


    【解决方案1】:

    只需将您的facts 设置为一个数组,然后使用Math.random()Math.floor() 随机选择一个

    if(data.country_name == 'India'){
        $('.fact').append("<h2 id='india'>Fact about India</h2>");
        let facts = [
           "The world's highest cricket ground is in Chail, Himachal Pradesh. Built in 1893 after leveling a hilltop, this cricket pitch is 2444 meters above sea level.", 
           "fact2",
           "fact3",
           "fact4"];
        $('.fact').append('<p>' + facts[Math.floor(Math.random()*facts.length)] + '</p>')
        console.log('this a india');
        // ...
    

    【讨论】:

      【解决方案2】:

      您可以通过向对象或数组中的数据添加一些结构来减少大量代码重复,并根据data.country.name查找您需要的内容

      类似:

      const countries = {
         'India': {
              id: 'india',
              title: 'Facts about India',
              facts: ['I-1','I-2', 'I-3','I-4']
         },
         'Turkey': {
              id: 'turkey',
              title: 'Facts about Turkey',
              facts: ['T-1','T-2', 'T-3','T-4']
         }
      }
      
      const item = countries[data.country_name],
            fact = item.facts[Math.floor(Math.random()*item.facts.length)],
      
            $head = $('<h2>',{id: item.id, text: item.title}),
            $p = $('<p>',{text: fact));
      
      $('.fact').append($head, $p);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-15
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-09
        相关资源
        最近更新 更多