2

$roleOption誰かが追加画像をクリックしたときにオブジェクト ( ) を挿入したい。else 条件は正常に機能し、まさに私が望むとおりに機能します。

しかし、最初の条件 (「オプションがない場合は画像の直前に挿入する」) はまったく機能しません。エラーは発生せず、オブジェクトを先頭に追加しません。

prepend メソッドを間違って使用していますか?

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        var $roleOption = "<div class='roleoption'><img src='@Url.Content("~/Public/images/delete.png")' alt='delete' />@Html.Raw(@DSS.WebUI.Helpers.CustomHelpers.SelectListItemsForRoleJavascript(Model.ExistingRoles, 1))</div>";

        $('img.add-role').click(function() {
            if ($(this).siblings('.roleoption').length == 0) {

                //Displaying zero as expected. So it's entering this conditional.
                console.log($(this).siblings('.roleoption').length); 
                $(this).prepend($roleOption); //However the element isn't being prepended. :/
            }
            else {
                $($roleOption).insertAfter($(this).parent().find('.roleoption:last')); //This works as expected.
            }
        });
    });
</script>
4

1 に答える 1

4

コンテンツをタグに挿入することはできません<img>(これprepend()がしようとしていることです)。

before()代わりに使用してください。

于 2012-02-01T03:15:36.177 に答える