首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript或Jquery通过div的键获取div并更改它的值

Javascript或Jquery通过div的键获取div并更改它的值
EN

Stack Overflow用户
提问于 2016-12-15 12:12:53
回答 1查看 228关注 0票数 0

我有一张桌子的清单。

代码语言:javascript
复制
var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
    if (data[i].current_order == null) {
        tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
    } else {
        tables += '<button class="table_selected" key="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
    }

桌子有两种颜色,忙的时候和不忙的时候。如果表中有current_order,则显示忙。我想要做的是,当用户单击空表时,它将获取table_id,将类从table_btn更改为table_selected,并添加key的div,即current_order

我使用phoenix-framework作为后端,所以当用户单击一个空表时,它会创建order并传递所单击的table_id和创建的order_id的值。但是我不确定如何通过table div的value获取一个表,并将key放入div…

有人能给我这个建议吗??

EN

回答 1

Stack Overflow用户

发布于 2016-12-15 12:34:55

所以当你给Jquery加标签的时候,我要发布这篇文章。将密钥更改为ID,您可以执行以下操作。然后,我会在函数中包装add table和remove table,在函数中传入data[i].current_order并使用它。

基于用户反馈编辑的,未经测试的

代码语言:javascript
复制
/*If you are not comfortable using the variable 'This',
  you can just pass in the id of target table and 
  change the syntax to $("#"+targetTable)*/

var tables = "";
for (var i = 0; i <= data.length - 1; i++) {
    if (data[i].current_order == null) {
        tables += '<button class="table_btn" value="' + data[i].id + '">' + data[i].table_number + '</div>';
    } else {
        tables += '<button class="table_selected" id="' + data[i].current_order + '"value="' + data[i].id + '">' + data[i].table_number + '</div>';
    }

// On Click set table to busy
$(".table_btn").click(function(){
   addTable($(this).val(), $(this));
});

// Add table function
function addTable(tableId, targetTable){
  $.ajax({
  url: "YourBackEndHere",
  data: tableID
  cache: false,
  success: function(html){
        $(targetTable).removeClass("table_btn");
        $(targetTable).addClass("table_selected");
        $(targetTable).attr("id", data[i].current_order);
  }
 });
}

// On click set table to empty
$(".table_selected").click(function(){
  removeTable($(this).val(), $(this));
});

// Remove table function
function removeTable(tableId, targetTable){
  $.ajax({
  data: tableId
  url: "YourBackEndHere",
  cache: false,
  success: function(html){
        $(targetTable).removeClass("table_selected");
        $(targetTable).addClass("table_btn");
        $(targetTable).attr("id", "");
    });
  }
 });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41156308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档