为什么val()返回undefined?

时间:2013-01-18 11:59:12

标签: javascript jquery

我尝试在单击按钮时获取下一个隐藏输入字段的值,但我的脚本始终返回“未定义”。我做错了什么,为什么val()返回undefined?如果只尝试使用next('input:hidden')选择元素,则该函数返回一个对象。

        <div class="row-fluid">
            <div class="span12">
                <div class="message-ratebox">
                    <ul class="unstyled inline">
                        <li>
                            <button class="rating-button" id="rating-first" value="1">
                                Er will dich
                            </button>1
                        </li>
                        <li>
                            <button class="rating-button" id="rating-second" value="2">
                                Er will dich nicht
                            </button>5
                        </li>
                        <li>
                            <button class="rating-button" id="rating-third" value="3">
                                Es ist alles offen
                            </button>2
                        </li>
                    </ul>
                    <input type="hidden" name="target_message_id" value="1" />
                </div>
            </div>
        </div>
        <div class="row-fluid">
            <div class="span12">
                <div class="message-ratebox">
                    <ul class="unstyled inline">
                        <li>
                            <button class="rating-button" id="rating-first" value="1">
                                Er will dich
                            </button>1
                        </li>
                        <li>
                            <button class="rating-button" id="rating-second" value="2">
                                Er will dich nicht
                            </button>5
                        </li>
                        <li>
                            <button class="rating-button" id="rating-third" value="3">
                                Es ist alles offen
                            </button>2
                        </li>
                    </ul>
                    <input type="hidden" name="target_message_id" value="2" />
                </div>
            </div>
        </div>

JavaScript的:

$(document).ready(function() {
    $('button.rating-button').click(function(event) {
        event.preventDefault();
        var $rating = $(this).attr('value');
        var $messageId = $(this).next('input:hidden').val();

        alert('test'+$messageId);
    });
});

1 个答案:

答案 0 :(得分:0)

        $('button.rating-button').click(function(event) {
            event.preventDefault();
            var $rating = $(this).val();
            var $messageId = $(this).parent().parent().parent().find('input').val();
            alert($rating + $messageId );

           });