简体   繁体   English

将动态字符串值传递给函数

[英]Pass dynamic string value to function

I have an array of names and over 100 geographic coordinates. 我有一个名称数组和100多个地理坐标。 I am dynamically creating an appended HTML table of the 5 closest coordinates to a specified address. 我正在动态创建最接近指定地址的5个坐标的附加HTML表。 I want to do a conditional statement based on the selected address in the list of 5 closest addresses. 我想根据5个最接近的地址列表中的选定地址来执行条件语句。 I am able to pass the numeric values to a supporting function but the string value isn't being passed to the function, which is required for the conditional logic. 我能够将数字值传递给支持函数,但字符串值没有传递给函数,这是条件逻辑所必需的。 if i plug in the value i as the parameter for showRouteB() then the function will work, however when i try to plug in city.name or variable assigned to city.name then the function doesn't seem to get called. 如果我将值i作为showRouteB()的参数插入,则该函数将起作用,但是,当我尝试插入city.name或分配给city.name的变量时,该函数似乎没有被调用。 i couldn't find any errors when i checked the console in Chrome and i've tried several different variations. 当我在Chrome中检查控制台并且尝试了几种不同的版本时,我找不到任何错误。 does anyone see any obvious syntax or logic errors? 有人看到任何明显的语法或逻辑错误吗?

My code is: 我的代码是:

            for (i = 0; i < 5; i++) {
            city = top101citiesUS[i];                                       
            //dynamically load map_table                
            tbody += '<tr>';
            tbody += '<td>';
            tbody += '<a href=#'+city.name+' onclick=showRouteB('+city.name+')>' +city.name+ '</a>';

            //tbody +=  city.name +  city.lat + ',' + city.lng;
            tbody += '</a>';
            tbody += '</td>'
            tbody += '</tr>';
            }

.....i then append string values for table header + table body + table footer ..... i然后为表头+表体+表脚附加字符串值

    function showRouteB(x){ 
     var element = document.getElementById('ProuteB');  
     element.innerHTML = "This is the city name " + x;                  
    }

您需要在字符串周围添加引号,否则将它们视为变量。

tbody += '<a href=#'+city.name+' onclick=showRouteB("'+city.name+'")>' +city.name+ '</a>';

The answer from Levi helped me on my way however the resolution was that the array of values, such as Charles Street, Smith Ave, and Vanburen Lane contained spaces that required a %20. Levi的回答对我有帮助,但是解决方案是,诸如Charles Street,Smith Ave和Vanburen Lane之类的值数组包含需要%20的空格。 When the value was passed to the function then it was being interpreted as "showRouteB('Smith " and it created a logical syntax error since the "')" was missing. 将该值传递给该函数后,该值将被解释为“ showRouteB('Smith”),由于缺少“')”,因此创建了逻辑语法错误。 I had to remove the whitespace from my array of values in order to find the problem. 为了找到问题,我不得不从值数组中删除空格。 Levi, thanks for the reply! Levi,谢谢您的回复!

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

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