0

我试图用 jquery 获取 html 标记的属性值。

    $query = "SELECT * FROM frontpage_modules";
        mysql_query("SET NAMES 'utf8'");
        $result = mysql_query($query) or (mysql_error());
        while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $list[] = $row['module_name'];
            $name[] = $row['name'];
            $img[] = $row['img'];
            $link[] = $row['link'];
            $module_content[] = $row['module_content'];
        }
    ?>


  <form action="ChangeFrontpageModule.php" method="post">  
   <ul id="gallery">
            <?php

                for ($idx = 0; $idx < count($list); $idx+=1) {
                    echo "<li data-itemid='" . $idx . "'>";
                    echo "<div class='drag_div'>";


                    echo '<div class="kundeutsagn">';
                    echo '<img src="http://www.amedisin.no/pictures/artikler/'.$img[$idx].'" alt="Top5"  title="Top5" />';
                    echo '<div class="statement_top">';
                    echo '<h5>'.$name[$idx].'</h5>';
                    echo "<input type='text' name='title' value='".$name[$idx]."' />";
                    echo $module_content[$idx];
                    echo '</div></div>';


                    echo "</div>";
                    echo "</li>";
                }
            ?>
        </ul>
    </form> 

我正在尝试传递存储在数据项中(在 li 内)的 ID 和输入元素中的值。

通过此代码“var title = $(this).val();”,我能够从输入元素中获取数据,但属性值返回错误“未定义”

下面是返回错误的jquery脚本

   <script>
        $(function() {
    $('h5').click(function() {
        $(this).slideUp().next('input').slideDown();
    });
    $('ul#gallery input').change(function() {
        var id = $(this).parent('li').attr('data-itemid');
        var thisParam = $(this);
        var title = $(this).val();
        $.ajax({
            type: 'POST',
            url: 'JavaScript/ChangeFrontpageModule.php',
            data: 'title=' + title + '&id=' + id,
            success: function(response) {
                $('input').slideUp();
                $(thisParam).prev('h5').text(title).slideDown();
                $('#response').fadeIn(1000).empty().append(response).prepend('<span id="x">X</span>');
                $('span#x').click(function() {
                    $('div#response').fadeOut('slow');
                });
            }
        });
    });
});
        </script>
4

1 回答 1

2

You are asking for the data-itemid attribute from $(this).parent('ul'), but the attribute in the first snippet you posted is on the <li> elements, not on the <ul>.

Edit: Taking a closer look, the input is also not a direct descendant of the li. Use closest() instead.

So if you switch $(this).parent('li') to $(this).closest('li') you should be fine.

Credit to @wirey's comment for closest(), I had mistakenly suggested parents()

于 2012-11-15T20:06:02.440 回答