将 jquery 附加到特定的 id 和类

Append with jquery to particular id & class

本文关键字:id 和类 jquery      更新时间:2023-09-26

我似乎无法附加到特定的id和类。我希望 HEllow 世界只被附在 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>

两个问题:

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

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

如果你纠正了这两个问题,你会没事的。请注意,如果您有唯一的 id s,则不再需要"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>

现场示例 | 来源


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

那么一定是这样的

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

这是没有空格的$('#94.m'),这意味着 id 和类都必须存在才能匹配