javascript - Does a clicked on item go out of scope when going into the getJSON section -


when clicking on list item, go out of scope when going getjson section want go , data database?

i have list of items displaying colours. each list item has id set of sku. when click on list item, must go , data database sku , populate contents on page.

i playing around code , interest's sake wanted see if change text of clicked on list item. after json call done, tried set text, nothing happened.

i sku of clicked on list item this:

var sku = this.id; 

after json call tried set text of clicked on list item this:

this.text('sample text'); 

i tried:

this.text('sample text'); 

here full javascript/jquery code:

<script>      $(document).ready(function () {           $('.attributes li').click(function () {                var url = 'www.example.com/test-url';                var sku = this.id;                $.getjson(url, { sku: sku }, function (data) {                     // not work                     this.text('sample text');                });           });      }); </script> 

here html markup:

<ul class="list-inline attributes selectable">      <li id="sku0001">blue</li>      <li id="sku0002">green</li>      <li id="sku0003">red</li>      <li id="sku0004">yellow</li> </ul> 

when going getjson section this go out of focus? clicked on list item go out of scope?

yes!! when gets .getjson, this loose context , this refer callback function of $.getjson , no more referring li. suggest create instance of this outside $.getjson var that=this , assign that.text inside $.getjson

example:

$(document).ready(function () {      $('.attributes li').click(function () {            var that=this;            var url = 'www.example.com/test-url';            var sku = this.id;            $.getjson(url, { sku: sku }, function (data) {                  // here not work because refers callback function                  that.text('sample text'); //assign referred            });       }); }); 

alternatively, if using ajax add option called context refer this anywhere inside ajax

$('.attributes li').click(function () {     var url = 'www.example.com/test-url';     var sku = this.id;     $.ajax({         url : url,         datatype : 'json',         data:{sku:sku},         context : this, //add         complete : function (data) {             // 'this' passed context              $(this).text('sample text')         }     }); }); 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -