简体   繁体   English

获取JQuery数据-包含带空格的值

[英]Get JQuery data- that contains value with spaces

I have two functions: in the first one, I'm setting the data-file_name attribute using JQuery: 我有两个功能:在第一个功能中,我使用JQuery设置data-file_name属性:

 "<input type=\"image\" + " data-file_name=" + result.fileName/>"

Which works great, but when I'm trying to retrieve that value from the second function if the data-file_name value contains spaces I just get the first word(for example if data-file_name= "The book blue" I just get The , if data-file_name = "Red Dragon" I just get on the second function Red it stops when it find an space... ) This is the way I'm retrieving the value in the second function: 效果很好,但是当我尝试从第二个函数中检索该值(如果data-file_name value包含空格)时,我只会得到第一个单词(例如,如果data-file_name= "The book blue"我只会得到The ,如果data-file_name = "Red Dragon"我刚上第二个函数Red它在找到空格时就会停止...)这是我在第二个函数中检索值的方式:

var fileName = $(this).data("file_name");

So fileName variable will not get the real value because it doesn't include anything behind the spaces, which way should I use to retrieve the value complete including spaces and everything? 所以fileName variable将不会获得真实值,因为它不包含空格后面的任何内容,我应该使用哪种方式来检索包含空格和所有内容的完整值?

There is a concatenation problem. 存在串联问题。

Replace with this 用这个替换

"<input type=\"image\" data-file_name=\"" + result.fileName + "\" />"

What you're creating isn't valid syntax. 您所创建的语法无效。

// Invalid Syntax:
<input type="image" data-red dragon="" />

When you template or even produce this input via the server, the markup can't have a space on the data attribute. 当您通过服务器进行模板化甚至生成此输入时,标记的data属性上不能有空格。 Though it allows some customization. 虽然它允许一些自定义。 The reason it fails with the space is because it is concating "Red" to your data attribute, but then treating "Dragon" as another attribute. 空格失败的原因是因为它会将“红色”隐藏到您的数据属性中,然后将“龙”视为另一个属性。

In essence, this is being created: 本质上,这是在创建:

<input type="image" data-red="" dragon="" />
<input type="image" data-red="" />

Both aren't what you intended. 两者都不是您想要的。 You would need to do remove the space, to correctly build that data attribute. 您需要删除空间以正确构建该数据属性。 Your other option would be to place the filename as the value, rather than in the data attribute. 您的另一个选择是将文件名作为值而不是data属性。 For instance: 例如:

<input type="image" data-filename="@FileName" />

Obviously, you would use whatever approach to generate where I placed @FileName . 显然,您将使用任何方法来生成我放置@FileName Also you could use single quotes, then physically use double quotes to help simplify concatenation in JavaScript. 另外,您可以使用单引号,然后在物理上使用双引号来帮助简化JavaScript中的串联。

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

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