简体   繁体   中英

Missing HTML Attribute Value With Spaces from jQuery

I have some jQuery where I am appending text where some of their attributes take some js variables.

<script>
var className = "COS 102";
var teacher = "Bob Teacher";

$("#classesDiv").append("<div className="+className+" teacher="+teacher+" class='class'></div>");
</script>

The issue I am having is that when I pass these variables into the element it comes out looking like className="COS" , without the 102 after.

Does anybody know why this is happening?

Because you don't have quotes around the attribute values.

Your code is going to append:

<div className=COS 102 ...

when it should append

<div className='COS 102' ...

This should work:

<script>
var className = "COS 102";
var teacher = "Bob Teacher";

$("#classesDiv").append("<div className='"+className+"' teacher='"+teacher+"' class='class'></div>");
</script>

Think about the string you're appending:

<div className=COS 102 teacher=Bob Teacher class='class'></div>

Since those attribute values aren't quoted, 102 and Teacher are seen as separate, value-less attributes. You'll want to get:

<div className='COS 102' teacher='Bob Teacher' class='class'></div>

by quoting:

$("#classesDiv").append("<div className='" + className + "' teacher='" + teacher + "' class='class'></div>");

Or, to be more jQuery-ish about it:

$('<div>').
  attr({
    'className' : className,
    'teacher' : teacher
  }).
  appendTo($('#classesDiv'));

An advantage to the last approach: it works even if teacher or className contain quotes (either single or double), or other characters that are meaningful to HTML.

It's happening because you're constructing an element by joining strings together. As you can see, this approach is fragile. Construct the element by passing an object to jQuery's $ function:

var className = 'COS 102';
var teacher = 'Bob Teacher';

$('<div>', {
    className: className,
    teacher: teacher,
    'class': 'class'
}).appendTo('#classesDiv');

Also, custom attributes like className and teacher are not valid HTML. You must prefix them with data- :

$('<div>', {
    'data-className': className,
    'data-teacher': teacher,
    'class': 'class'
})

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