javascript - 如何根据元素类将元素元素属性附加到span

标签 javascript jquery html

我的目标是根据用户点击的选项数量,在 h4 标签内包含三个或更少的选择。

例如,如果没有选择任何元素或具有类 active,则 h4 标记应为 'Department1,Department 2',然后将其回退到 默认类。

到目前为止,我只能将 1 个项目附加到我的 h4 标签中。我在写这篇文章时遇到了麻烦。

我这里有一个 JS Fiddle 文件//http://jsfiddle.net/breezy/h5812bsc/

正如您所看到的,当您单击一个部门时,它会向该项目添加一个 active 类,然后将文本附加到 h4 标记,但如果我选择另一个选项,它会删除以前附加的项目,并且追加新的。

简单来说,我需要在 h4 标签内使用 span 标签连接两个或三个部门,如果没有选项使该类处于事件状态,则将其回退到 default 类。不知道我如何才能实现这一点。一些指导或提示会有所帮助。谢谢

jQuery

// When user clicks on any option it will replace the text to the last selected item
// dependant on the title attribute of the anchor tag
$('.selected-options a.option-btn').click(function (e) {
    e.preventDefault();

    // make the title attribute a variable for use later
    var text = $(this).attr('title');

    $(this).toggleClass('active');

    if ($('.selected-options a.option-btn').hasClass('active')) {

        $(this).parent().parent().parent().parent().parent().find('.toggle-this h4').empty().append(text);

    }


});

最佳答案

一些小改进,

  1. $('.selected-options a.option-btn')$(this).parent().parent() 可以存储到变量中,所以我们不需要一次又一次地查找它们。

  2. 正如您所评论的,全部我们切换所有其他按钮的状态,因此我们可以添加简单的检查来查看当前项目是否为全部(这里我使用默认类,可能与您的真实网络有所不同),并在我们单击全部时切换所有其他元素状态。

  3. 然后我们可以使用.map获取 jquery 包装的 title,并使用 .get将其转换为数组。当您评论说您只想显示某些项目时,我们可以使用 length 来检查事件项目是否超出限制,并在必要时进行剪辑。

  4. 最后,我们可以轻松使用 join使用给定的分隔符将 array 转换为 string

// When user clicks on any option it will replace the text to the last selected item
// dependant on the title attribute of the anchor tag

// Create references for frequently used elements, so we don't need to 
// call jquery to get them each time.
var $place = $('.department .toggle-this h4');
var $targets = $('.selected-options a.option-btn');

// Maxlimit to clip further choices.
var maxLimit = 2;
// Text to replace the clipped items.
var clippedText = '...';

$targets.click(function (e) {
    e.preventDefault();
    
    // Create a ref to the jquery wrapped object, so we don't need to 
    // call `$(this)` whenever we need to use it.
    var $this = $(this);
    $this.toggleClass('active');
    // If all is selected, toggle others.
    if ($this.hasClass('default')) {
        $targets.not('.default').toggleClass('active', $this.hasClass('active'));
    }
    
    // Get all active departments to an array.
    var actives = $targets.filter('.active').not('.default').map(function() {
        return $(this).attr('title');
    }).get();
  
    // Clip the array to limit
    if (actives.length > maxLimit) {
        actives = actives.slice(0, maxLimit)
        actives[maxLimit - 1] += clippedText;
    } else if (actives.length === 0) {
       // If nothing is choose, set to default value.
        actives.push('any');
    }
    
    // Set text by join the concatenate the items in array with `, `.
    $place.text(actives.join(','));

});
a {
    text-decoration:none;
}
.selected-options ul {
    width: 90%;
    padding: 15px 0;
    margin: 0 auto;
}
.selected-options li {
    text-align: center;
    margin: 0 auto;
    padding: 4px 0;
    list-style:none;
}
.selected-options li a {
    border:1px solid #ccc;
    width: 99%;
    text-decoration:none;
    padding:3px 5px;
    border-radius:5px;
}
.selected-options li a.active {
    border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="department narrow-option">
    <div class="mobile-inner toggle"> <a href="#" class="toggle-this"><h3>Department:</h3> <h4>Any</h4></a>

    </div>
    <div class="additional-info hide">
        <div class="selected-options" id="department-selections">
            <ul>
                <li><a href="#" title="All" class="option-btn default">All</a>

                </li>
                <li><a href="#" title="Department 1" class="option-btn">Department 1</a>

                </li>
                <li><a href="#" title="Department 2" class="option-btn">Department 2</a>

                </li>
                <li><a href="#" title="Department 3" class="option-btn">Department 3</a>

                </li>
            </ul>
        </div>
        <!-- eo // selected-options -->
    </div>
    <!-- eo // additional-info -->
</div>
<!-- eo // department -->

关于javascript - 如何根据元素类将元素元素属性附加到span,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32766314/

相关文章:

javascript - JSLint:控制注释(选择性忽略)

php - FileReader javascript 类不适用于 IE

javascript - 获取编辑页面的用户数组

javascript - Google Maps API 3 - 绑定(bind)后删除圆圈

php - 表的奇数行和偶数行

php - ajax多次上传php文件处理

html - 自动以半步包裹 Flexbox 元素

html - 无法设置模态内部元素的tabindex

javascript - 响应式或设备有条件地加载 JavaScript 文件

html - 支持 Microsoft Edge 的多范围 slider