0

我发现这个链接非常有用

获取选定的文本框 id jQuery

但是,我现在想做的是重用这个 id 来为它实际循环的每个文本框做一些修剪功能。我试过这段代码:

<html>
    <head>
        <?php   echo $this->Html->script("jquery-1.4.3.min"); ?>

    </head>
    <body>
    <?php
        echo $content_for_layout;
    ?>
    <script type="text/javascript">
        $(document).ready(function () {
         //       alert('JQuery is succesfully included');

/*      $(':submit').click(function(){
            <?php if(($this->request->controller=='members')&&($this->action=='register')):?>
                    //alert('well');
                    var some = $.trim($(":text").val());
                    alert(some);
            <?php  endif; ?>

            });
*/
            $(':submit').click(function(){
                $('form input[type="text"]').each(function(){
                    //get value of id of textbox here
                    var id = $(this).attr('id');
                    var some = $.trim($((this).attr('id')).val());
                    alert(some);
                });

            });
        });
    </script>
    </body>
</html>

但它不会弹出警报框。

4

1 回答 1

0

我对您要实现的目标感到有些困惑,但是这一行存在问题:

var some = $.trim($((this).attr('id')).val());

具体来说,(this).attr('id')不起作用,因为(this)它被解释为this并且this是当前没有.attr()方法的 DOM 元素。

你可能想这样做:

var some = $.trim($("#" + $(this).attr('id')).val());
// or, given you already have a variable id equal to $(this).attr('id')
var some = $.trim($('#' + id).val());

也就是说,您试图从当前元素中获取 id,然后使用该 id 选择元素并获取其值,然后修剪该值。但是你不需要 id 来获取值,因为你已经引用了元素 - 你可以这样做:

var some = $.trim($(this).val());
// or
var some = $.trim(this.value);

如果您想遍历所有文本框并将它们设置为当前值的修剪版本,您可以这样做:

$('form input[type="text"]').each(function(){
    this.value = $.trim(this.value);
    // or if you want the slower and harder to read way:
    $(this).val( $.trim($(this).val()) );
});

或者:

$('form input[type="text"]').val(function(i,currentVal) {
    return $.trim(currentVal);
});

有关将.val()回调函数传递给.val().

于 2012-05-10T00:48:15.427 回答