【问题标题】:Getting the value of the selected cells in jQuery在jQuery中获取选定单元格的值
【发布时间】:2018-01-12 06:27:10
【问题描述】:

我正在使用一些免费脚本在单击表格单元格时突出显示它。它可以多次单击,因此我可以一次选择多个单元格。当我单击单元格时,我想检索它们的值并显示到下面的输入中,以便在完成突出显示后发布它。我的脚本如下所示:

function displayVals(item) {
        var multipleValues = $(this).html() || [];
        $("p.info").html("<b>Multiple:</b> " + multipleValues.join(", "));
        alert($(item).html()); 
        $("#clicked").val(multipleValues.join(", "));
    }

    $(document).ready(
        function(){
            $('#table3').highlight('td');
            $('#table3').highlight('td', 'highlight-selected', 'mousedown');
            $('#table3 td').click(function() { 
                displayVals(this);
            });

        }
    );

displayVals 函数的这个例子中,我使用alert 来显示我现在选择的单元格。它显示没有问题,但在名为 clicked 的输入中没有粘贴任何内容,p.info 中也没有出现任何内容。

如果有人可以帮助我,我将不胜感激。

【问题讨论】:

  • 哦。在 displayVars 中,当我在 mullipleValues 中使用 item 时,定义了警报窗口崩溃,但什么也没发生。
  • 你已经在alert中使用了item,crash是什么意思?
  • 带有item 的警报显示在屏幕上,但带有itemitem 在multipleValues 中的警报停止显示警报。

标签: jquery html-table cell


【解决方案1】:

在点击事件中this 只指向被点击的元素而不是所有的tds。

$('#table3 td').click(function() { 
     displayVals(this);
});

.html() 返回一个字符串,因此您不需要连接,并且您使用 this 而不是 item

function displayVals(item) {
    var multipleValues = $(item).html() || '';
    $("p.info").html("<b>Multiple:</b> " + multipleValues);
    alert($(item).html());
    $("#clicked").val(multipleValues);
} 

列出所有多个值

function displayVals(item) {
  var multipleValues = [];
  $(item)
    // Search the parrent table
    .closest('table')
    // Get any highlight selected td
    .find('td.highlight-selected')
    // Iterate and add the html to multipleValues
    .each(function(){ multipleValues.push($(this).html()) })


    $("p.info").html("<b>Multiple:</b> " + multipleValues.join(", "));
    alert(multipleValues.join(", "));
    $("#clicked").val(multipleValues.join(", "));

} 

【讨论】:

  • 如下所述。当我在multipleValues 中点击$(item) 时,什么也没发生。看看演示kam1ll0.vot.pl/hi.php
  • 是的,我们很接近了。但我想要多个值,现在输入值会根据新值擦除。我想用逗号分隔
  • 对不起,不工作。什么都没发生。也许别的东西?谢谢你。
  • 抱歉有错别字,请使用each 而不是foreach
  • 嘿Ghommey!我自己已经想通了。就在你写答案的同时!另一个错误在“foreach”行中。 html 标记中缺少 ()。比它完美地工作。请更正您的解决方案,而不是我将其设置为“正确答案”。非常感谢!干杯
猜你喜欢
  • 2017-03-04
  • 2018-03-10
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多