在表中使用JQuery切换跨度文本

Switch span text using JQuery in a table

本文关键字:文本 JQuery      更新时间:2023-09-26

我有一个程序生成的表,列出了数据库中的信息。你可以在这里看到:

http://www.homeducate.me/cgi-bin/browseTutors.cgi?Lui=en&countryCode=MO

对于一段文本,如果它很长,我会列出文本的缩短版本。现在,当用户单击该行以展开下面的其他行时,我想将其切换到较长的版本。

我的表格有一组重复的部分,如下所示:

<tr class="header">
 //some stuff
<script>
  var approachTxt1 = "Shortened version of the text...";
  var approachFullTxt1 = "Full length version of the text to be displayed.";
</script>
<td><img src="an_image.png"><span id="approach1">Shortened version of the text...</span><img src="another_image.png"></td>
//some more stuff
</tr>
<tr>Some more rows of stuff</tr>

然后,我使用以下脚本(1)最初将所有行折叠到每个标题行下,(2)在单击标题行时将它们切换为再次显示(3)如果用户单击未隐藏的行,则重定向到url,(4)在表上时将指针更改为鼠标。一切都很顺利。

<script>
    $('#listTutors .header').each(function () {
        $(this).nextUntil('tr.header').toggle();
    });
   $('.header').click(function () {
    var $this = $(this);
      $(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
      });
 
    });
  
    $("tr:not('.header')").click(function () {
      top.window.location.href="http://www.homeducate.me/cgi-bin/createAccountForm.cgi?Lui=en";
    });
    $('html,table').css('cursor','pointer');
</script>

现在我想做的是,当用户单击以展开该部分时,将文本的缩短版本切换为全文,然后当用户再次单击以隐藏该部分时再次将其切换回缩短形式。我一直在尝试:

     $(this).next('span').html($(this).next('span').html() == approachTxt1 ? approachFullTxt1 : approachTxt1);

但我得到了";undefined不是函数";以及";意外字符串";错误。它显然没有拾取当前标头之后的跨度。

此外,我正在努力思考如何对我的每一组表行进行这种更改(例如,根据用户选择的标题行切换出适当的字符串)。我已经在这个问题上挠头太久了:(非常感谢任何指导。

好了,终于想出了怎么做。在这里发帖,以防将来对其他人有所帮助。。。。

首先,我为表的每个部分设置了一个唯一的id:

<tr class="header" id="$nnn">

其中$nnn是由我的Perl程序驱动的,只是1,2,3等。

然后,对于表的每个部分,我将短文本字符串和长文本字符串放入数组的元素中:

<script>
   approachTxt[$nnn] = "short version of the text";
   approachFullTxt[$nnn] = "long version of the text which will be switched in and out";
</script>

然后我的脚本变成:

<script>
    $('#listTutors .header').each(function () {
        $(this).nextUntil('tr.header').toggle();
    });
    $('.header').click(function () {
    var $this = $(this);
      $(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
      });
     $('#span' + this.id).html($('#span' + this.id).html() == approachTxt[this.id] ? approachFullTxt[this.id] : approachTxt[this.id]);
    });
    $("tr:not('.header')").click(function () {
      top.window.location.href="http://www.homeducate.me/cgi-bin/createAccountForm.cgi?Lui=en";
    });
    $('html,table').css('cursor','pointer');    
</script>

现在一切都很顺利。我今晚可以睡得更好:)