简体   繁体   中英

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:

 "<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:

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?

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. 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. For instance:

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

Obviously, you would use whatever approach to generate where I placed @FileName . Also you could use single quotes, then physically use double quotes to help simplify concatenation in JavaScript.

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