动态更改列表元素上的模态内容单击

时间:2015-11-13 01:20:53

标签: javascript jquery html css

我有一个html页面,模拟社交网络网站的新闻源。在这里,来自不同用户的帖子在无序列表上生成为li。我想在点击上显示一个弹出模式,即使这些列表元素中的任何一个都会动态显示该特定列表元素的内容。标记如下:

<body>  
    <div class="container" >


        <ul id="newsfeed">
            <li class="news" data-toggle="modal" data-target="#myModal">

                <img src="someimage_1.png" class="img-thumbnail" alt="Cinque Terre" width="60" height="60">
                <p class="title">jhon</p>
                <p class="text">good moprning every body</p>
                <p>posted at 12:30pm</p>

                <hr>

            </li>

            <li class="news" data-toggle="modal" data-target="#myModal">

                <img src="someimage_1.png" class="img-thumbnail" alt="Cinque Terre" width="60" height="60">
                <p class="title">jimmy</p>
                <p class="text">hello every body</p>
                <p>posted at 12:30pm</p>

                <hr>

            </li>

            <li class="news" data-toggle="modal" data-target="#myModal">

                <img src="someimage_1.png" class="img-thumbnail" alt="Cinque Terre" width="60" height="60">
                <p class="title">joe</p>
                <p class="text">felling bored at home</p>
                <p>posted at 12:30pm</p>

                <hr>

            </li>

        </ul>


        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body" id="popup">
                    <p>Some text in the modal.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
          </div>
        </div>

    </div>
</body>

我试过JQuery:

<script>
    $('#myModal').on('show.bs.modal', function (event) {
        var element = $(event.relatedTarget); // the li that triggered the modal to show
        var dynamic_text = element.find('.text').val(); // Extract the value of the .text div inside that li
        var modal = $(this);
        $("#popup").html('the users post says: ' + dynamic_text);
    });
    </script>

1 个答案:

答案 0 :(得分:2)

.popup是类,而不是id。需要改变

  modal.find('.popup').text('the users post says: ' + dynamic_text);

  $("#popup").html('the users post says: ' + dynamic_text);

并更改val以发送文字:

 var dynamic_text = element.find('.text').text();

小提琴http://jsfiddle.net/6oh9aacL/1/