简体   繁体   English

使用jQuery动态分配ID到元素

[英]Dynamically assigning ID to an element with jQuery

I have a table cell with a dynamically assigned id like this, 我有一个具有这样动态分配的ID的表格单元,

    <tbody>
      {% for item in thread_model %}
      <tr>
       .....
        <td id="{{ item.id }}" class='btn vote_up'>{{ item.id }} Vote Up</td>
        <td id="{{ item.id }}" class='btn vote_down'>{{ item.id }} Vote Down</td>
        <td id="voted{{ item.id }}">{{ item.vote }}</td>
        ........
      </tr>
      {% endfor %}
    </tbody>

This works fine and then I have a bit of ajax which calls a Django view. 这可以正常工作,然后我有一些ajax调用了Django视图。 But then I wish to set the innerHTML of that cell. 但是然后我希望设置该单元格的innerHTML。 But how do I get the jQuery to put the innerHTML into the table cell with the same id as the row of the vote up or down which I pressed? 但是,如何获取jQuery,将innerHTML放入具有与我按下的上下投票行相同的ID的表单元格中?

$(document).ready(function() {
  $('.vote_up').on('click', function() {
    $.get("/vote_up/" + this.id + "/", function(data) {
      $('#voted' + this.id).innerHTML = data;
    });
  });
  $('.vote_down').on('click', function() {
    $.get("/vote_down/" + this.id + "/", function(data) {
      $('#voted' + this.id).innerHTML = data;
    });
  });
});

The urls, 网址,

url(r'^vote_up/(?P<id>\d+)/$', home.vote_up, name='vote_up'),
url(r'^vote_down/(?P<id>\d+)/$', home.vote_down, name='vote_down'),

The views look like this, 风景看起来像这样

def vote_up(request, id):
    posts = PostModel.objects.get(pk = id)
    posts.vote += 1
    PostModel.objects.filter(pk=id).update(vote=posts.vote)
    return HttpResponse(posts.vote, content_type="text/plain")

def vote_down(request, id):
    posts = PostModel.objects.get(pk = id)
    posts.vote -= 1
    PostModel.objects.filter(pk=id).update(vote=posts.vote)
    return HttpResponse(posts.vote, content_type="text/plain")

Thanks 谢谢

this.id is undefind inside $.get . $.get this.id undefind SO you should change your code like this 所以你应该这样改变你的代码

$(document).ready(function() {
      $('.vote_up').on('click', function() {
        var id = this.id;
        $.get("/vote_up/" + id + "/", function(data) {
          $('#voted' + id).html(data);
        });
      });
      $('.vote_down').on('click', function() {
        var id = this.id;
        $.get("/vote_down/" + id + "/", function(data) {
          $('#voted' + id).html(data);
        });
      });
    });

You can use Jquery addClass() method to assign classes dynamically to an element. 您可以使用Jquery addClass()方法将类动态分配给元素。

Example : 范例:

$("#ID").addClass("selected");

Or if you just want to add an style to and element you can use css() method 或者,如果您只想向和元素添加样式,则可以使用css()方法

Example: 例:

$("#ID").css( "color", "red" );

Hope this may help you 希望这对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM