JavaScript / jQuery - 从文本的选择菜单中获取选项属性

时间:2015-05-20 10:29:36

标签: javascript jquery html

这是我的HTML:

<select name="Pcolor" id="image" style="height:30px;">
    <option value="">Избран цвят: Blue/Lt Blue </option>
    <option value="45751303" color-number="0">Black</option>
    <option value="45751343" color-number="1">Black/Pink</option>
    <option value="45751359" color-number="2">Blue/Lt Blue</option>
    <option value="45751324" color-number="3">Dk Purple/Purpl</option>
    <option value="45751390" color-number="4">Ink/Cerise</option>
</select>

这是我的Javascript:

var ColorSelectt = $('#image').find('option[text="Black/Pink"]').attr("color-number");
alert(ColorSelectt);

我想要做的就是从标识为image的选择菜单中找到具有文字(非值)Black/Pink的选项,然后获取color-number=""中包含的值

当警报出现时,它会给我回复undefined,为什么会这样?

我该如何解决?

2 个答案:

答案 0 :(得分:3)

使用:contains content filter选择包含指定文字的所有元素。

var ColorSelectt = $('#image option:contains("Grey M/Navy")').attr("color-number");
var ColorSelectt2 = $('#image option:contains("Navy/Grey M")').attr("color-number");

alert(ColorSelectt + ':' + ColorSelectt2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="Pcolor" id="image" style="height:30px;">
    <option value="">Избран цвят: Blue/Lt Blue </option>
    <option value="45751303" color-number="0">Black</option>
    <option value="45751343" color-number="1">Black/Pink</option>
    <option value="45751359" color-number="2">Blue/Lt Blue</option>
    <option value="45751324" color-number="3">Dk Purple/Purpl</option>
    <option value="45751390" color-number="4">Ink/Cerise</option>
    <option value="45751390" color-number="5">Grey M/Navy</option>
    <option value="45751390" color-number="6">Navy/Grey M</option>
    
</select>

答案 1 :(得分:0)

尝试:

    var ColorSelectt = $('#image').find('option:contains("Black/Pink")').attr("color-number");
    alert(ColorSelectt);

jsfiddle:https://jsfiddle.net/cw6knsc5/

或:

 var ColorSelectt = $('#image option:contains("Black/Pink")').attr("color-number");
    alert(ColorSelectt);