1

我正在尝试使这行代码正常工作。

$(".selectnumber").text($(this).parent().find('select').children(':selected').text());

它只是想获取选择的文本值并将其放在 selectnumber 范围内。

alert($(".selectnumber").parent().find('select').children(':selected').text()); 

工作正常并返回正确的值,所以我必须假设 $(this) 没有像我期望的那样引用 .selectnumber 跨度。

继承人的 HTML 以防它影响任何东西,但我认为它不会。

<div class="holder">
    <span class="selectnumber"></span>
    <select id="number_of_cards_required" name="number_of_cards_required">
        <option selected="selected">1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
</select>
</div>
4

5 回答 5

1

我必须假设 $(this) 没有像我预期的那样引用 .selectnumber 跨度。

对,那是正确的。您期望this引用您选择的元素,仅仅是因为您正在对它们调用函数。但是,您只是将参数传递给函数,此时它与您调用该函数的对象无关,因此这没有多大意义。

但是,您可以将一个函数传递给.text()jQuery 方法,以便您使用它this来引用该特定匹配元素。

$(".selectnumber").text(function () {
    return $(this).parent().find('select').children(':selected').text()
});
于 2013-05-24T10:15:15.937 回答
0

利用

$(".selectnumber").html( your text )

不是

$(".selectnumber").text( your text )
于 2013-05-24T10:10:06.360 回答
0

this必须在有意义的上下文中使用,作为触发器。您可以尝试以下方法:

$(".selectnumber").html($("#number_of_cards_required").val());

编辑:

如果您value为选项输入 a 并且仍然需要文本,则可以使用:

$('#number_of_cards_required option:selected').text()
于 2013-05-24T10:10:23.493 回答
0

您需要使用.html()而不是text(). 也许您还希望每次选择更改时都更新跨度:

    $(".selectnumber").html($('#number_of_cards_required').val());


       $('#number_of_cards_required').change(function(){
    $(".selectnumber").html($('#number_of_cards_required').val());
});

看看这个jsfiddle

于 2013-05-24T10:14:39.173 回答
0
$(function() {

//initial loading
$(".selectnumber").text($(".selectnumber").parent().find('select').children(':selected').text());  

//changing span if select changes

$("select").change(function() {
$(".selectnumber").text($(this).parent().find('select').children(':selected').text());        
    })
})

http://jsfiddle.net/ACf4Y/

于 2013-05-24T10:15:16.807 回答