简体   繁体   English

在javascript中传递包含空格的字符串

[英]pass string containing white spaces in javascript

I have a div class like this and want to call setlocation function which will set the value of the state in the text box 我有一个像这样的div类,想调用setlocation函数,该函数将在文本框中设置状态的值

<div class="overview over_widt">
    <ul>
        <li class="auto" title="All India"></li>
        {% for state_obj in state_list %}
            <li name="state" class="auto" title="{{state_obj.name}}"><a href="#{{state_obj.id}}" onclick=javascript:setlocation("{{state_obj.name}}")> {{ state_obj.name }}</a></li>
         {% endfor %}
    </ul>

my java script function 我的Java脚本功能

function setlocation(name){
    //alert(name);
    $('#id_autocomplete').val(name);
    document.getElementById('city_state').style.display="none"
}

and my textbox 和我的文本框

<input type="text" class="text2" name="location" id="id_autocomplete" placeholder="Enter Location" onfocus="show_div();" onkeyup="div_autocomplete()"/>

The problem is I have some states which have "whitespaces" in them and passing those parameters is creating a problem . 问题是我有一些状态中包含“空格”,传递这些参数会造成问题。 I tried passing the object also like 我也尝试传递对象

onclick=javascript:setlocation("{{state_obj}}")

but this also doesnt work. 但这也不起作用。

You have to put the HTML attribute value in quotation marks: 您必须将HTML属性值放在引号中:

onclick="setlocation('{{state_obj.name}}')"

Otherwise values with whitespace will mess up your HTML. 否则,带有空格的值会使您的HTML混乱。 If you don't use quotation marks, then only the characters up to the next whitespace are considered to be part of the value. 如果不使用引号,则只有下一个空格之前的字符才被视为该值的一部分。 So if the generated HTML was 因此,如果生成的HTML是

onclick=setlocation("foo bar")

Then you would have an attribute onclick with value setlocation("foo and a boolean attribute bar") (though this would probably be invalid, I don't think attribute names can contain " or ) ). 然后,您将获得一个具有值setlocation("foo and boolean attribute bar")的属性onclick (尽管这可能无效,但我认为属性名称不能包含") )。

But really, instead of using inline event handlers, you could use event delegation or any other way of binding event handlers . 但实际上,您可以使用事件委托任何其他绑定事件处理程序的方式来代替使用内联事件处理程序

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

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