更改了选择选项时jQuery更改最近的跨度显示样式

时间:2015-10-09 10:08:24

标签: jquery html css twitter-bootstrap

我有这个块:

<div class="user-select-dropdown">
    <span class="filter-header">User:</span>
    <span class="remove-option">✖</span>
    <select class="form-control" ng-model="filter.UserId" ng-change="filterModel(filter)" ng-options="item.Id as item.Name for item in usersList">
       <option value="" disabled selected>Select user...</option>
    </select>
</div>

我使用X的范围是重置select选项的按钮,但当select没有任何选项时,我的删除选项为display: none;,我需要当我改为任何选项时显示它。 我有这个css:

.remove-option {
    display: none;
    bottom: 14%;
    color: darkgrey;
    font-size: 15px;
    position: absolute;
    right: 7%;
    z-index: 99999;
    cursor: pointer;
}

.user-select-dropdown {
    position: relative;
    display: inline-block;
    margin-left: 10px;
    width: 250px;
}

这个jquery:

$(".remove-option").click(function () {
    $(this).next("select").val($("select option:first").val());
});

$(".form-control").change(function () {
    if ($(this).val() >= 0)
        $(this).next(".remove-option").css("display: block");
    else
        $(this).next(".remove-option").css("display: none");
});

.form-control是bootstrap类。

问题是$(this).next(".remove-option").css(...)无效,请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

由于remove-option元素位于form-control之前,您必须使用prev而不是next

$(".form-control").change(function () {
    if ($(this).val() >= 0)
        $(this).prev(".remove-option").css("display: block");
    else
        $(this).prev(".remove-option").css("display: none");
});

答案 1 :(得分:0)

如果你查看你的html,span是form-control元素的前一个兄弟,所以使用.prev()

$(".form-control").change(function () {
    $(this).next(".remove-option").toggle($(this).val() >= 0);
});

您还可以使用.toggle()在一行中更改显示,如上所述

因为看起来你正在使用angularjs

&#13;
&#13;
var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.usersList = [{
    Id: 1,
    Name: '1'
  }, {
    Id: 2,
    Name: '2'
  }, {
    Id: 3,
    Name: '3'
  }, {
    Id: 4,
    Name: '4'
  }];
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
  <div class="user-select-dropdown">
    <span class="filter-header">User:</span>
    <span class="remove-option" ng-show="filter.UserId > 0">✖</span>
    <select class="form-control" ng-model="filter.UserId" ng-change="filterModel(filter)" ng-options="item.Id as item.Name for item in usersList">
      <option value="" disabled selected>Select user...</option>
    </select>
  </div>
</div>
&#13;
&#13;
&#13;