显示符合所需参考的正确项目

时间:2017-12-13 10:08:47

标签: javascript jquery html arrays

我的问题是我无法显示需要在表格中查看的确切信息。

例如,假设我有一个按钮dataGridView并且我检索了一个对象数组:

Show

所以我有一个表格,每行有两行和两个按钮 - "data": [ { "short_desc": "Lorem Ipsum Short", "long_desc": "Lorem Ipsum Long", }, { "short_desc": "Lorem Ipsum Short", "long_desc": "Lorem Ipsum Long", } ] 。在第一次单击时它应该显示第一个对象,在第二次它应该显示第二个对象。因此,将数组中的键与正确的Show按钮匹配。我怎样才能做到这一点?

我知道这可能是一个“老问题”,但我已经远离编程并忘记了这个算法。

感谢。

编辑:在评论后编辑。

所以,我首先收到数据:

Show

现在使用$.ajax({ type: 'GET', url: 'url' }).done(function(res) { var data = res.data // here logic goes }) 按钮显示数据。

现在我需要创建一个处理程序,以便在按钮单击时显示确切的数据。

2 个答案:

答案 0 :(得分:1)

我不知道这是否是您要搜索的内容,下面的代码段在btn上显示匹配的data-id对象,点击使用jquery

var json = {
  "data": [{
      "short_desc": "Lorem Ipsum Short 1",
      "long_desc": "Lorem Ipsum Long 1 ",
    },
    {
      "short_desc": "Lorem Ipsum Short 2 ",
      "long_desc": "Lorem Ipsum Long 2 ",
    },
    {
      "short_desc": "Lorem Ipsum Short 3 ",
      "long_desc": "Lorem Ipsum Long 3 ",
    }
  ]
}

$(".btn").on("click",function(){
  var id = $(this).data("id");
  if(!isNaN(id)) {
    var data = json.data[id-1];
    if(data){
      $("#short").html(data.short_desc);
      $("#long").html(data.short_desc);
    }
    else {
      $("#short").html("");
      $("#long").html("");
    }
  }
  else {
    $("#short").html("");
    $("#long").html("");
  }
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><button class="btn" data-id="1">Show 1</button></td>
    <td><button class="btn" data-id="2">Show 2</button></td>
    <td><button class="btn" data-id="3">Show 3</button></td>
    <td><button class="btn" data-id="4">Show  no data</button></td>
  <tr>
<table>

<div>
  <div>
  Short desc : 
    <p id="short"><p>
  </div>
  <div>
  long desc :
    <p id="long"></p>
  </div>
</div>

答案 1 :(得分:0)

您可以为每个按钮指定自己的类,以便您可以区分它们,例如在jQuery中:

$(buttons).on('click',
              function () {
                  if ($(this).hasClass('firstButton'))
                         // show first button
                  else if ($(this).hasClass('secondButton'))
                         // show second button
               });

对于许多按钮,您可以在编写时为每个按钮提供增量ID,以及相关的类。然后,除了检查hasClass之外,您还可以使用$(this).attr('id'),并且在它们之间应该可以识别需要哪个精确的数组元素。