Jquery - 显示2个选择之间的关系

时间:2018-05-08 13:40:15

标签: javascript php jquery bootstrap-modal

我使用PHP,MySQL,Bootstrap模式和Jquery创建了一个网站模块。我有4个带数据的复选框。我将数据存储在数据库中。如果客户选择2个复选框,则会出现一个引导模式,其中包含2个选择之间的关系。它确实有效,但模态会多次显示数据。

在这种情况下,computer1连接到计算机3,计算机3连接到计算机4。因此,如果我选择computer1和computer4,它会正确显示关系,但有几次:

Bootstrap Modal



$(document).ready(function() {
  $('#checkBtn').click(function getElementRelation(element1, element2) {
    var ele = document.getElementsByName("case");
    var modal = document.getElementById("modaldata");
    var hu = document.getElementsByName("hu");
    var hu2 = document.getElementsByName("hu2");

    if (modal.innerHTML === "") // if no relation is detected yet put start element
    {
      modal.innerHTML += element1;
    }

    //loop in data (this shows datas several times)
    for (var i = 0; i < ele.length; i++) {
      if (hu[i].innerHTML === element1) //if data = element 1 then put related element
      {
        modal.innerHTML += hu[i].innerHTML + "--->" + hu2[i].innerHTML + " ";
        if (hu2[i].innerHTML !== element2) //if related element != end element call function to get relation between related element and end element
        {
          getElementRelation(hu2[i].innerHTML, element2);
        }
      }
    }

    var start = ""; //hold start element
    var end = ""; //hold end element
    for (var i = 0; i < ele.length; i++) {
      if (ele[i].checked === true) {
        if (start === "") {
          start = hu[i].innerHTML; //set start element
        } else {
          end = hu[i].innerHTML; //set end element
        }
      }
    }

    checked = $("input[type=checkbox]:checked").length === 2;
    if (!checked) {
      alert("You must check 2 checkbox!");
      return false;
    } else {
      getElementRelation(start, end);
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />


<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Checkboxes -->



<div class="container">
        <div class="row">
            <div class="col-sm-6">
                <table class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th></th>
                            <th>Name</th>
                            <th>Connect</th>
                        </tr>
                    </thead>
                    <tbody>
                        
                        <tr>
                            <!-- Checkboxes -->
                            <td><input type="checkbox" name="case"></td>
                            <td><p name="hu" value="Computer1">Computer1</p></td>
                            <td><p name="hu2" value="Computer3">Computer3</p></td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" name="case"></td>
                            <td><p name="hu" value="Computer2">Computer2</p></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" name="case"></td>
                            <td><p name="hu" value="Computer3">Computer3</p></td>
                            <td><p name="hu2" value="Computer4">Computer4</p></td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" name="case"></td>
                            <td><p name="hu" value="Computer4">Computer4</p></td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

<!-- Input button -->
<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <input type="button" id="checkBtn" value="View" data-toggle="modal" data-target="#myModal" class="btn btn-info">
    </div>
  </div>
</div>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Title</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body" id="modaldata">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

选择Computer1和Computer3并多次显示数据

1 个答案:

答案 0 :(得分:0)

首先,段落标记没有任何属性namevalue。如果要创建新属性,请使用HTML5 data-attributes

为了使后续的JS代码更容易,我们将这些属性添加到input元素中。例如,

<tr>
    <td><input type="checkbox" name="case" data-name="Computer1" data-connect="Computer3"></td>
    <td>Computer1</td>
    <td>Computer3</td>
</tr>

其次,你的JS代码有点令人困惑。我猜你得到重复结果的原因是因为你递归地调用了getElementRelation()

我会简化您的代码,如下所示

$(function() {
    // cache jQuery objects that we will be re-using
    var checkBoxes = $("input[name=case]");
    var myModal = $("#myModal");

    // get all relationships i.e. key = name, value = connect or null
    var relations = {};
    checkBoxes.each(function () {
        relations[this.dataset.name] = this.dataset.connect;
    });

    // when the getElementRelation() function is called normally, it is expected 
    // to have 2 arguments (element1 and element2); 
    // but as an event handler it will have 1 argument (Event object) 
    $('#checkBtn').click(function getElementRelation(e) {

        // get checked checkboxes
        var checkedBoxes = checkBoxes.filter(":checked");

        // validate first
        if (checkedBoxes.length != 2) {
            alert("You must check 2 checkbox!");
            return false;
        }

        // build modal body
        var html = '';

        var current = checkedBoxes[0].dataset.name,
            end = checkedBoxes[1].dataset.name;

        while (current) {
            html += current;

            // check if it is connected
            var next = relations[current];

            // if it is not connected, stop
            if (!next) {
                html = 'Not related';
                break;
            }

            // otherwise append HTML
            html += ' -> ' + next + '<br>';

            // if it is the end, stop
            if (next == end) break;

            // you may want to delete the key to avoid any infinite loop in case
            // delete relations[current];

            // start over using connected one
            current = next;
        }

        // update modal
        myModal.find('.modal-body').html(html);

        // open the modal dynamically once it is ready
        myModal.modal('show');
    });
});

最后一件事,请回到您的HTML中,删除data-toggle="modal"data-target="#myModal",因为我们opening the modal dynamically

<强>演示

$(function() {
  // cache jQuery objects that we will be re-using
  var checkBoxes = $("input[name=case]");
  var myModal = $("#myModal");

  // get all relationships i.e. key = name, value = connect or null
  var relations = {};
  checkBoxes.each(function() {
    relations[this.dataset.name] = this.dataset.connect;
  });

  $('#checkBtn').click(function() {
    // get checked checkboxes
    var checkedBoxes = checkBoxes.filter(":checked");

    // validate first
    if (checkedBoxes.length != 2) {
      alert("You must check 2 checkbox!");
      return false;
    }

    // build modal body
    var html = '';
    
    var current = checkedBoxes[0].dataset.name, // start with
      end = checkedBoxes[1].dataset.name; // end with
      
    while (current) {
      html += current;

      // check if it is connected
      var next = relations[current];

      // if it is not connected, stop
      if (!next) {
        html = 'Not related';
        break;
      }

      // otherwise append HTML
      html += ' -> ' + next + '<br>';

      // if it is the end, stop
      if (next == end) break;

      // start over using connected one
      current = next;
    }

    // update modal
    myModal.find('.modal-body').html(html);

    // open the modal dynamically once it is ready
    myModal.modal('show');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Checkboxes -->
<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th></th>
            <th>Name</th>
            <th>Connect</th>
          </tr>
        </thead>
        <tbody>

          <tr>
            <td><input type="checkbox" name="case" data-name="Computer1" data-connect="Computer3"></td>
            <td>Computer1</td>
            <td>Computer3</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="case" data-name="Computer2"></td>
            <td>Computer2</td>
            <td></td>
          </tr>
          <tr>
            <td><input type="checkbox" name="case" data-name="Computer3" data-connect="Computer4"></td>
            <td>Computer3</td>
            <td>Computer4</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="case" data-name="Computer4"></td>
            <td>Computer4</td>
            <td></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Input button -->
<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <input type="button" id="checkBtn" value="View" class="btn btn-info">
    </div>
  </div>
</div>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Title</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body" id="modaldata">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>