1

我有一个在网站上运行的 Twitter Bootstrap 轮播。轮播代码是使用 Smarty 模板生成的。我有很多其他的轮播使用相同的代码运行,但是关于这个的一些事情让我很伤心。图像旋转得很好,但是当我单击推进轮播的控件之一时出现错误。这是我在 Firebug 中遇到的错误:

TypeError: $active.attr(...) is undefined   
, curId = $active.attr('id').substring(7) (bootstrap.js, line 343)

(Chrome 会抛出关于未定义元素的子字符串未定义的警告)

如果你手头没有副本,这里是 bootstrap.js 的相关部分:

, slide: function (type, next) {
var $active = this.$element.find('.item.active')
, $next = next || $active[type]()
, isCycling = this.interval
, direction = type == 'next' ? 'left' : 'right'
, fallback = type == 'next' ? 'first' : 'last'
, that = this
, e = $.Event('slide', {
relatedTarget: $next[0]
})
, curId = $active.attr('id').substring(7)

此错误的最可能原因似乎是当前没有任何 .item 元素(轮播图像)是 .active。或者活动轮播元素没有 ID。但是我可以通过查看 Firebug 中的代码来判断这些事情都没有发生。

如果有帮助,这里是生成轮播控件的 Smarty 代码,显示每个元素都有一个 ID,并且第一个元素被分配了一个 .active 类:

<div class="text-control">
            {foreach from=$articles item=article name=artforeach}
                <a {if $article.source|strlen > 7}href="{$article.source}"{else}href="javascript:void(0)"{/if} 
                    {if $smarty.foreach.artforeach.first} class="active"{/if} id="name{$article.id}" 
                    data-target="{$smarty.foreach.artforeach.index}">
                    <h3>{$article.name}</h3>
                    <p>{$article.teaser[0].content|strip_tags|truncate:100:"..."}</p>
                </a>
            {/foreach}
        </div>

有人知道这里可能发生了什么吗?

4

1 回答 1

0

经过一整天的尝试和检查代码,我发现问题与“事件冒泡”的概念有关。虽然 .active 类、ID 和 data-target 都应用于 a 元素,但 click 事件实际上是由 a 元素内部的 h3 元素处理的。而且由于 h3 没有类 .active 或 ID 或数据目标,所以轮播失败了。我认为这可能与 h3 元素的特殊块级状态有关,但是如果您将 span 元素或 i 元素放入其中,也会发生这种情况。

此代码有效:

<div class="text-control">
            {foreach from=$articles item=article name=artforeach}
                <a {if $article.source|strlen > 7}href="{$article.source}"{else}href="javascript:void(0)"{/if} 
                    {if $smarty.foreach.artforeach.first} class="active"{/if} id="name{$article.id}" 
                    data-target="{$smarty.foreach.artforeach.index}">
                    {$article.name}
                    <p>{$article.teaser[0].content|strip_tags|truncate:100:"..."}</p>
                </a>
            {/foreach}
        </div>

我所做的就是删除 h3 标签。有趣的是, p 标签似乎根本不影响事件冒泡。只要 a 元素的开头有纯文本,其他一切似乎都很好。

于 2013-07-16T00:13:52.037 回答