3

我试图让一个“a”标签在由 ajax 调用创建后聚焦。

代码如下:

    <form method="post" id="submitrow">
        <table>
            <tr>
                <td>
                    <input name="quantity" id="id_quantity" />
                </td>
                <td>$
                    <input name="price" id="id_price" />
                </td>
                <td><span id="add_row"></span>

                </td>
            </tr>
        </table>
    </form>

    <script>
    jQuery("#id_quantity").change(function () {
        jQuery('#add_row').html('<a onclick="document.forms[\'submitrow\'].submit();" id="sbmbtn">click me</a>');

        jQuery('#sbmbtn').focus(); // I want to focus the new link, it does not works

        alert(jQuery('#sbmbtn').is(':focus')); // it should be True!

        jQuery('#sbmbtn').live("keyup", function (e) {
            if (e.keyCode == 13) {
                alert('whoot whoot!');
            }
        });
    });

    jQuery("#id_quantity").focus();
    </script>

似乎 html 替换后 DOM 没有正确更新。也许我必须以不同的方式替换代码?

我用我的代码的简化版本创建了一个小提琴,它重现了这个问题。

提前感谢您提供的任何提示!:)

4

1 回答 1

2

只需在标签上设置 tabindex

jQuery("#id_quantity").change(function () {
    jQuery('#add_row').html('<a tabindex="11" onclick="document.forms[\'submitrow\'].submit();" id="sbmbtn">click me</a>');

    jQuery('#sbmbtn').focus(); // I want to focus the new link, it does not works

    alert(jQuery('#sbmbtn').is(':focus')); // it should be True!

    jQuery('#sbmbtn').live("keyup", function (e) {
        if (e.keyCode == 13) {
            alert('whoot whoot!');
        }
    });
});

jQuery("#id_quantity").focus();
于 2013-02-01T15:55:33.117 回答