【问题标题】:How to use a JQuery click event to render JSON data?如何使用 JQuery 点击事件来呈现 JSON 数据?
【发布时间】:2019-04-30 17:23:14
【问题描述】:

* 我并不懒惰——我已经阅读了许多支持线程,但不理解它们或不知道如何推断我的代码。我是新手,希望能给予指导。 *

我使用了来自工作委员会的 API 数据。我有数据渲染。我希望隐藏职位描述并仅在用户单击按钮时显示。我正在尝试使用 JQuery 来完成此操作。我已经尝试了一些 JQuery 代码,它使用硬编码数据和 alert()。现在,我需要弄清楚如何让它与我使用的 JSON 格式的 API 数据一起工作。

使用 JQuery,我如何从我的 json 数据中获取职位描述以仅在单击按钮时显示?

我试图将description=''; 放在曾经是硬编码数据的位置,我添加了$(document.body).append(event.data.description); 来呈现数据(代替 alert() 所在的位置)

这是 JQUERY 代码:

// JQUERY EVENT HANDLER 
$(document).ready(function(){
  $('#btnClickMe').on('click', {
     description: '',

  }, jobDesc);

  function jobDesc(event)
  {
    $(document.body).append(event.data.description);

  }
});

Here is my HTML:

<!DOCTYPE html>
<html lang="en">
<head>

 <title>JQuery Testing</title>  

</head>
  <body>

   <!-- DIV FOR CARD DISPLAY -->
     <div id="root"></div>

     <!-- CARD -->
     <div class="container-fluid">
      <div class = "card">
        <input id="btnClickMe" type="button" value="Click Me"/>
     </div>
   </div>

   </body>
</html>

这是我在 codepen 上的完整代码:https://codepen.io/CodeDuchess/pen/jRRvgy

预期的结果是,当单击按钮时,它将显示完整的职位描述(不必在新窗口中打开)。

实际结果是单击按钮时什么都没有发生,并且在页面首次加载时工作描述就在那里。

任何指导将不胜感激!!非常感谢!!

【问题讨论】:

  • 这是几个问题。如果您花时间一步一步地寻找答案,可以在 SO 上找到所有答案。
  • 我现在正在为您解答。我会为你“jQuery-ify”这段代码,这会给你一个很好的开始使用 jQuery。
  • @TimothyWood 谢谢!感谢您的宝贵时间。
  • 没问题。如果我的回答很好 - 如果可以,请标记它。

标签: jquery json api onclicklistener


【解决方案1】:

我们开始吧。以下应该作为如何在 jQuery 中完成所有这些操作的一个不错的示例。另请参阅此处工作示例的代码笔:https://codepen.io/xonosnet/pen/PgvaWq

CSS

.hidden {
  display:none!important;
}
.card:hover {
  cursor:pointer;
}

JS

'use strict';


//Clean up API URL to make it easy to configure.
var app = {
        baseUrl : 'https://cors-anywhere.herokuapp.com/https://jobs.github.com/',
        target: 'positions.json',
        params : {
            markdown:true,
            location:'united states',
            page:1,
            count:20
        },
        url : '',
        data : '',
        root : $('#root')
    };
    app.url = app.baseUrl+app.target+'?'+$.param(app.params); //$.param() encodes the params object to be used in the http request.

app.root.append('<div class="container1"></div>'); //Easy way to append inline html to an existing element.
var container1 = $('.container1'); //Reference the newly created element by class using css selectors. You can reference elements by any attribute.


//$.getJSON() is a quick & easy way to retrieve JSON through an http request.
var request = $.getJSON(app.url, function(data) {
    app.data = data; //This executes first
}).done(function() { //This executes second - This is called chaining.
    console.log('[SUCCESS] Found '+app.data.length+' jobs!');
    //$.each() will iterate objects & arrays.
    $.each(app.data, function(index, job) {
        const output = [
            '<div class="card" data-id="">',
            '   <h2>'+job.title.substring(0, 40)+(job.title.length > 40 ? '...':'')+'</h2>',
            '   <h3>'+job.company+'</h3>',
            '   <h4>'+job.type+'</h4>',
            '   <h5>'+job.location+'</h5>',
            '   <p class="job-desc hidden">'+job.description.substring(0, 300)+(job.description.length > 300 ? '...':'')+'</p>',
            '</div>'
        ]; // This is one among many ways to build out html. I chose this because it's cheap & clean.
        container1.append(output.join('')); //Join the array into a string & append it to container1.
    });
});

// This will toggle the "hidden" class of the child nodes of any card that you click.
// A cleaner way of showing job details rather than displaying a button.
$(document).on('click', '.card', function() {
    var children = $(this).find('.job-desc');
    children.toggleClass('hidden');
});

//If you still want to use a button, this is how you can do that.
//Assuming the following exists in each card: <button class="show-job-btn">Click Me!</button>
$(document).on('click', '.show-job-btn', function() {
    var children = $(this).closest('.job-desc');
    children.toggleClass('hidden');
});

【讨论】:

  • 效果很好!我也很欣赏您通过许多 cmets 提供的清晰度。你是个好老师!!我希望我能请你喝一杯!我确实赞成您的解决方案,但它没有出现在我的最后。非常感谢,祝您度过愉快的一周!
  • 我很乐意为您提供帮助。您应该能够在某处将帖子标记为答案。这对我有很大帮助! :)
  • 已检查为解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
  • 2012-05-17
  • 1970-01-01
  • 2011-09-26
  • 2018-03-21
  • 1970-01-01
相关资源
最近更新 更多