简体   繁体   中英

Can a variable be passed as an element id in javascript

I'm trying to get some AJAX running with Django using jQuery. The problem is that the ID of the element I'm trying to change isn't set in stone, it's a Django template variable so it is different for each element in the table, but I want to use AJAX to change that element. I'm passing the dictionary from a Django view to JavaScript via simplejson, the pertinent objects being ID and model (not real variable names, just wanted to make it obvious what I am trying to do). Some pseudo code (third line, wrote it like python because I don't know how to do this in JavaScript):

var quantity_update = function(msg, elem) {
    var response_obj = eval('(' + msg + ')');
    var newtotal = document.getElementById("%s, %s"); % (response_obj.id, response_obj.model)
    subtotal.innerHTML = "<td>"+response_obj.subtotal+"</td>"; 

Is something like this possible, and if so how?

If your element ID is not set in stone, you might want to identify the element using other means. Many JS framework such as jQuery supports identification via CSS Selector. For example you can identify the element you want to change by combination of its tag and class.

For documentation on the available selector you should read jQuery Selector Documentation

Javascript doesn't have fancy string formatting (%s), but you can use plain string concatenation, just like you can in Python:

var id = response_obj.id + ', ' + resonse_obj.model

You don't need to worry about the string being generated dinamically. It is still a string after all and getElementById accepts it the same way .


You probably shouldn't be doing the eval() yourself to parse the JSON. I'm pretty sure you can have JQuery do that for you when you do the AJAX request.

You can totally pass jquery css selectors as variables. Simple example:

var elementId = $('td').eq(0).attr('id'),
    myElement = $('#'+elementId); 

In this example, we grab the ID of the first TD in your document, find its id, and use that to get "myElement"

You may find it helpful to review the "selectors" section of the jQuery documentation (api.jquery.com) to review all your options for finding an element. In my example I also am using the jquery.eq() method, which filters a list of selectors (in this case all the TDs) to a specific one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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