0

我有一个选择框在页面上使用了很多次。

<div class="some-div">
    <a class="maybe">Maybe</a>
    <select class="selectclass">
        <option>Maybe</option>
        <option>Yes</option>
        <option>No</option>
    </select>
</div>

我如何使用 jQuery 根据所选选项的数量向“a”元素添加一个类?因为该站点是多语言的,所以不能从值中获取类别,而是从选项的数量中获取类别:'maybe' 代表第 1 个,'yes' 代表第 2 个,'no' 代表第 3 个。该选择在页面上被多次使用,因此它应该只适用于正在运行的那个。

提前致谢!

4

4 回答 4

1

更新 - 根据 OP 的要求

您是否尝试像在此演示中所做的那样

jQuery:

$('.selectclass').change(function(){

    var number = $(this).val();
    var value = $("option^[value=" + number + "]").text();

    $(this).parent().find('a').html(value);    
    $(this).parent().find('a').attr('class', 'opt' + number);

});​

HTML:

<div class="some-div">
    <a class="opt1">Maybe</a>
    <select class="selectclass">
        <option value="1">Maybe</option>
        <option value="2">Yes</option>
        <option value="3">No</option>
    </select>
</div>​

CSS:

.opt1{ color:blue; }
.opt2{ color:green; }
.opt3{ color:red; }​
于 2012-08-06T10:55:06.770 回答
1

首先将您的 HTML 更改为使用选项“值”属性,这样您就不会关心多语言架构。

<div class="some-div">
<a class="maybe">Maybe</a>
<select class="selectclass">
    <option value="1">Maybe</option>
    <option value="2">Yes</option>
    <option value="3">No</option>
</select>

绑定到您的 ddl 更改方法并使用 jquery 查找您的 ddl 的值。

$('.selectclass').bind("change", function() {  
var option = $(this).val();
if (option == 1)
{
//your code
}
else if...
});
于 2012-08-06T10:58:11.623 回答
1

HTML

为您的选项添加一些值...

<div class="some-div">
    <a class="maybe">Maybe</a>
    <select class="selectclass">
        <option value="maybe">Maybe</option>
        <option value="yes">Yes</option>
        <option value="no">No</option>
    </select>
</div>​​​​​​

Javascript (jQuery)

选择器必须在实际代码中更加具体,以避免冲突......

// add a `change` event to the select element
​$("select").on("change",function(){
    // get the value of the select element
    var val = $(this).val()
    // remove all classes from the `a` tag  and add the
    // recently got value as a class of the `a` tag
    $("a").removeClass().addClass(val)
})​​​​​​​​​

CSS

只是为了测试...

​</p>

.no{
    color: red;
}
.yes{
    color: green;
}

.maybe{
    color: orange;
}
​

演示

预烘焙演示可以在这里看到:http: //jsfiddle.net/uBCJd/

于 2012-08-06T10:59:22.157 回答
0

这将为您提供所选选项的索引并更改链接的类和文本​</p>

$(".selectclass").live("change",function(){
    var index = $(this).children("option:selected").index() + 1;
    $(this).parent().find('a').text(index+':'+$(this).val());
    $(this).parent().find('a').attr('class',index);
});​
于 2012-08-06T11:01:38.830 回答