Django模板+jQuery+更好的方法



我想做一些类似流行图片游戏的事情,当你有一本图片集,并且必须回答图片的标题时,所以我使用Django+Kickstrap+jQuery(用于逻辑代码)

这是我的模板。

    <ul class="thumbnails" >
        <li class="span12" id="pops">
        {% for photo in pops.photos.all %}
            <div class="thumbnail span3" id="pop_picture">
              <img src="{{MEDIA_URL}}{{photo.original_image}}"alt="{{photo.name}}">
              <br>
              <p id="answer">{{photo.name}}</p>
              <input id="txt_pop" type="text"  value=""/>
              <button id="pops_button" type="submit"  class="btn">confere</button>
            </div>
        {% endfor %}
        </li>
    </ul>

--myscript.js

function myCallback() {
    //do things!;
    if( $("#txt_pop").val() === $("#answer").text())
    {
        $("#pops_button").addClass("btn-success");
        $("#pops_button").text("CORRETO");  
    }else{
       $("#pops_button").text("ERRADO");
       $("#pops_button").addClass("btn-danger");
   }
}
$(document).ready(function() {
    //and then change this code so that your callback gets run
    //when the button gets clicked instead of mine.
    // **by the way, this is jQuery!
    $('#pops').find("#pops_button").click(myCallback); 
});

发生了两件事,第一件:如何传递{{photo.name}},这就是答案,用于js上的函数。

第二种奇怪的行为是:我的第一个div类id="pop_picture"运行良好,任何其他图片都能很好地响应。

这个问题包括:jQuery新手和模板

对于多次出现的元素,不要使用id。这可能就是为什么只有你的第一个有效,而其他的无效。id="answer"也有同样的问题——使用一个类,并通过jQuery找到它。

{% for photo in pops.photos.all %}
        <div class="thumbnail span3" id="pop_picture">
          <img src="{{MEDIA_URL}}{{photo.original_image}}"alt="{{photo.name}}">
          <br>
          <p class="answer">{{photo.name}}</p>
          <input class="txt_pop" type="text"  value=""/>
          <button class="btn pops_button" type="submit">confere</button>
        </div>
{% endfor %}
$(document).ready(function() {
    $('#pops .pops_button').click(function() {
       alert($(this).parent().find('.answer').html());
    }); 

});

最新更新