简体   繁体   English

结合div ID和this.ID

[英]combine div ID and this.ID

Maybe isn't good title for the question but my problem is exactly this. 也许不是这个问题的好标题,但我的问题恰恰是这个。 I have several DIV tags on the page and all of them start as #result and continue with number <div id="result22"> , <div id="result33"> etc. Now I'm find some nice jQuery things to do and it works as expected but the only problem is how to add known number to the #result here is the code: 我在页面上有几个DIV标记,所有标记都以#result开头,并以数字<div id="result22"><div id="result33">等继续。现在,我找到了一些不错的jQuery要做的事情它可以按预期工作,但是唯一的问题是如何在#result添加已知数字,这是代码:

<script type="text/javascript">
   $(document).ready(function() {
     $('.like').bind('click', function () {
       $.get("/sng_like/"+this.id+"/", function(data) {
         $('#result')[0].innerHTML=data;
     });
   });
 });
</script>

I want that value of this.id to be a part of the #result to get #result22 for example. 我要的是价值this.id是一部分#result得到#result22例如。 My JS knowledge is limited and I was already try $('#result'+this.id)[0].innerHTML=data; 我的JS知识有限,我已经尝试过$('#result'+this.id)[0].innerHTML=data; but it wont work. 但它行不通。

Thanks, G 谢谢,G

$(document).ready(function() {
     $('.like').bind('click', function () {
       var item=$(this);
       $.get("/sng_like/"+item.attr("id")+"/", function(data) {
         $('#result'+item.attr("id")).html(data);
     });
   });
});

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. 从jQuery 1.7开始, .on()方法是将事件处理程序附加到文档的首选方法。 So you may consider using that. 因此,您可以考虑使用它。

If you are using 1.7+ version, your code can be rewritten to use on function like this 如果您使用的是1.7+版本,则可以将您的代码重写为在这样的函数上使用

$(function(){
   $(document).on("click",".like",function(){
       var item=$(this);           
       $.get("/sng_like/"+item.attr("id")+"/", function(data) {
          $('#result'+item.attr("id")).html(data);
       });
   });
});

$(function() is a short form of $(document).ready(function() $(function()$(document).ready(function()的缩写

你可以说:

$.get("/sng_like/"+$(this).attr("id")+"/", function(data)
<script type="text/javascript">
   $(function() {
       $('.like').on('click', function() {
           var MyId=this.id;
           $.get("/sng_like/"+MyId+"/", function(data) {
               $('#result'+MyId).html(data);
           });
       });
   });
</script>

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

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