简体   繁体   中英

Javascript: Getting variable name from HTML

I am attempting to create a reusable javascript / jQuery function where only the HTML will be editable. Basically, the jQuery script will look for a certain class on a form select element, and it will populate the select box. It's going to use an xml document, that will be fed into JavaScript variables.

<form>
    <select name="topliclist" class="mhs-events" data-event-xml="/xml/events.xml" data-event-text="$fullDate, at ,$startTime, - ,$location"></select>
</form>

In this example, 'fullDate', 'startTime' and 'location' are variables in the JavaScript:

//js
var fullDate = 'Monday, October 7';
var startTime = '6:30 PM';
var location = 'Office Building 1';

(don't worry about feeding the variable from xml, I can do that.)

The 'string' variable will equal the data-event-text:

//js
var string = '$fullDate, at ,$startTime, - ,$location';
$.each(string.split(","), function(index, item) {

            //remove $, only put this to specify that it is a variable
            if(item.indexOf('$') == 0) {
                item = $(item.substring(1));
                item = item.toString();
            }

            newString += item
        });

        $(this).append('<option>' + newString + '</option>');

Instead of 'Monday, October 7 at 6:30 PM - Office Building 1', it populates '[object Object] at [object Object] - [object Object];

What is the best way to get the variable name from the data-event-text attribute and actually use it to get the variable value in JavaScript?

Change

item = $(item.substring(1)); // this converts your string to object
item = item.toString();

to

item = item.substring(1);
item = eval(item).toString();

And you dont need to add every item into newString which will return all items as one option.

Try:

$.each(string.split(","), function(index, item) {
            //remove $, only put this to specify that it is a variable
            if(item.indexOf('$') == 0) {
                item = item.substring(1);
                item = eval(item).toString();
            }
           newString += item;
});
$('.mhs-events').append('<option>' + newString + '</option>');

DEMO FIDDLE

You can write a method as below

    function readString(el1, el2, el3, x) {

        var newStr = '';
        var temp = x.split(' ');
        for (var i = 0; i < temp.length; i++) {
            var str = temp[i];
            if (str.indexOf('$') == 0) {
                newStr += eval(str.substring(1, str.length));
            } else {
                newStr += str;
            }

            newStr += ' ';
        }

        return newStr;
    }

To call

readString("I", "am" ,"saying", "$el1 $el2 $el3 hello!!!")

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