简体   繁体   中英

Append with jquery to particular id & class

I cant seem to append to a particular id & class. I want HEllow world to be Appened to only 1st

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
var id =94;
    $("#'id',.m").append(" <b>Hello world!</b>");
  });
});
</script>
</head>
<body>
<p id="94" class="postitem m" >This is a paragraph.</p>
<p id="94" >This is another paragraph.</p>
<button>Insert content at the end of each p element</button>
</body>
</html>

Two problems:

  1. id values must be unique on the page. You're using the same id for two different elements.

  2. Your id values are invalid for CSS . id values for use with CSS must start with a letter. Since jQuery uses CSS selectors for finding elements, I'd strongly recommend using valid ones. (Those IDs are also invalid for HTML4 , but HTML5 allows them. Just not CSS.)

If you correct both of those problems, you'll be fine. Note that if you have unique id s, you don't need the "m" class anymore unless you were using it for something else.

<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    var id = 'x94';
    $("#" + id).append(" <b>Hello world!</b>");
  });
});
</script>
</head>
<body>
<p id="x94" class="postitem m" >This is a paragraph.</p>
<p id="x95" >This is another paragraph.</p>
<button>Insert content at the end of each p element</button>
</body>
</html>

Live example | source


Separately: I strongly recommend adding a doctype to that HTML. Without one, you're in quirks mode, and jQuery doesn't support quirks mode (various calculations will be wrong).

Then it must be like this

$('#'+id+'.m').append('<b>Hello world!</b>');

which is $('#94.m') with no spaces to mean that both id and class must exist to match

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