开发者

How to assign an id with the combination of letter and variable in jQuery?

开发者 https://www.devze.com 2023-04-11 15:49 出处:网络
I want to assign an id with the combination of letter and variable. Here is the sample cod开发者_Go百科e

I want to assign an id with the combination of letter and variable. Here is the sample cod开发者_Go百科e

$("#q1").append("<p id='q' + '"+ questionCount +"'>Question: " + questionCount + "<input type='text'>\
<button type='button' class='buttonMinus' id='"+ questionCount +"'></button></p>");

questionCount is a variable. I can only assign 'q' to each <p id> without the value of the questionCount, while I can assign the value of the questionCount to <button id>. I have tried several of format, but they still can't work. It really confused me.

Thanks Ashley


"<p id='q' + '"+ questionCount +"'>Question: " should be
"<p id='q"+ questionCount +"'>Question: ".

In your code, you're setting the ID of the element to q, and an (unwanted?) attribute which equals the value of questionCount.

Explanation:
Let questionCount be 9001, for this example
When the first part of your code is parsed, the following string operations are executed:

  • create <p id='q' + '
  • add questionCount
    <p id='q' + '13' (result)
  • add '>Question:
    <p id='q' + '13'> (result)

You cannot use + to concatenate attribute values in HTML. Your browser since + and '13' are invalid HTML attributes, they're ignored. As a result, the final first part is: <p id='q'>


it looks like your single quotes are out of whack

$("#q1").append("<p id='q" + questionCount +"'>Question: " + questionCount + "<input type='text'>\
<button type='button' class='buttonMinus' id='"+ questionCount +"'></button></p>");
0

精彩评论

暂无评论...
验证码 换一张
取 消