jQuery:在选择表时弹出一个对话框

时间:2014-11-18 02:36:28

标签: jquery select dialog popup

我需要在网页上选择表格时打开一个对话框。我可以使用table和mouseup函数的id元素打开对话框。但是这对于没有设置“id”字段的表格不起作用。我遇到了select,我可以看到它适用于输入元素,但我不能让它适用于表格元素

这是我目前的工作代码

function getSelected() {
    if (window.getSelection) {
        return window.getSelection();
    } else if (document.getSelection) {
        return document.getSelection();
    } else {
        var selection = document.selection && document.selection.createRange();
        if (selection.text) {
            return selection.text;
        }
        return false;
    }
    return false;
}

$('#test').mouseup(function () {
    var selection = getSelected();

    if (selection) {
        var arr = [];
        var vals = $('#test').find('td').filter(function () {
            //get only <td> that contain numeric value inside it
            return $.isNumeric(this.innerHTML);
        }).each(function (i, val) {
            arr.push(val.innerHTML);
        });
        alert(arr);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table id="test" style="width:100%">
    <tr>
        <td>Jill</td>
        <td>21</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>13</td>
        <td>94</td>
    </tr>
</table>
</div>

这仅适用于id字段设置为“test”

的表

以下是我尝试使用select的内容 它适用于输入但不适用于表格。

$( ":input" ).select(function() {
  $( "div" ).text( "table was selected" ).show();
});
$( ":table" ).select(function() {
  $( "div" ).text( "text was selected" ).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<body>
      <input type="text" value="Some text">
  <p>Click and drag the mouse to select text in the inputs.</p>
 <table id="test" style="width:100%">
    <tr>
        <td>Jill</td>
        <td>21</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>13</td>
        <td>94</td>
    </tr>
</table>     
  <div></div>
      </body>

请告诉我我做错了什么。 jQuery新手。谢谢 。

2 个答案:

答案 0 :(得分:1)

您需要使用element selector选择页面中的所有表格。 :input selctor是一个特殊的选择器,可以选择所有输入字段,例如inputselecttextareabutton

$( "table" ).select(function() {
  $( "div" ).text( "text was selected" ).show();
});

没有:table

这样的选择器

答案 1 :(得分:1)

您可以使用“表格”选择器选择页面上的所有表格。然后对每个表应用处理程序。在这种情况下,可以使用单击表格,因此请使用click事件。像这样:

$( "table" ).on('click', function() {
  $( "div" ).text( "text was selected" ).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<body>
      <input type="text" value="Some text">
  <p>Click and drag the mouse to select text in the inputs.</p>
 <table id="test" style="width:100%">
    <tr>
        <td>Jill</td>
        <td>21</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>13</td>
        <td>94</td>
    </tr>
</table>     
  <div></div>
      </body>