无法在H3标记内更改SPAN标记的文本,该标记具有不应随jQuery更改的其他文本

时间:2012-08-03 17:05:54

标签: jquery click html

我的目标是,当用户点击<div class="title">时,包含<span>内的<h3>内的文字会发生变化,再次点击它会返回到之前的位置值。

<div class="title">
    <h3>Text The Doesn't Change <span>Text That Changes</span></h3>
</div>

然而,当我点击div时,无论我点击多少次,文本都会更改一次然后停止。

如果我从代码中删除跨度之前的文本:

<div class="title">
    <h3><span>Text That Changes</span></h3>
</div>

然后它工作正常但我需要该文本出现在我的特定应用程序中。

这是我的jQuery代码:

$('div.title').click(function(){
    $(this).children('h3').children('span').text($(this).text() == '-' ? '+' : '-');;
});

以下链接指向我的网页:Demo

2 个答案:

答案 0 :(得分:2)

.children(...)替换为.find(...) - 在您的第一个代码块中,<span>实际上是文本节点的直接子节点,而不是<h3>。使用.find会根据需要深入查找<span>

<强>更新

您在this方法中使用.text()并未指出您的想法。请尝试使用回调函数:

$('div.title').click(function(){
    $(this).find('span').text(function(i,t) {
        return (t=='-') ? '+' : '-';
    });
});​

答案 1 :(得分:0)

在这种情况下,您正在访问错误的元素(div.title):

$(this).text() == '-' ? '+' : '-'

这应该是:

$('h3 > span', this).text() === '-' ? '+' : '-'

所有这些都可以简化为:

$('div.title').click(function(){
  var $span = $('h3 > span', this);
  $span.text($span.text() === '-' ? '+' : '-');
});

相关问题