附加jquery到特定的id&类

时间:2012-05-12 08:17:25

标签: javascript jquery append

我似乎无法附加到特定的id&类。我希望HEllo世界只能在第一次

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

2 个答案:

答案 0 :(得分:4)

两个问题:

  1. id 必须 在页面上是唯一的。您对两个不同的元素使用相同的id

  2. 您的id值为invalid for CSS。用于CSS id值必须以字母开头。由于jQuery使用CSS选择器来查找元素,我强烈建议使用有效的元素。 (这些ID对于HTML4也无效,但HTML5允许这些ID。不是CSS。)

  3. 如果你纠正了这两个问题,你会没事的。请注意,如果您有唯一的id,则除非您将其用于其他内容,否则不再需要“m”类。

    <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


    另外:我强烈建议在该HTML中添加doctype。没有一个,你处于怪癖模式,jQuery不支持怪癖模式(各种计算都是错误的)。

答案 1 :(得分:2)

Then it must be like this

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

$('#94.m'),没有空格表示id和class必须存在才能匹配