【问题标题】:Find Class name then remove id #查找类名然后删除 id #
【发布时间】:2017-01-14 18:13:40
【问题描述】:

您好,我正在尝试从具有通用类名的 div 中删除所有 id:

$('div.panel-group').removeAttr('id', '');

但不起作用。我不想要(例如找到 id 然后删除 id),因为有一堆生成的 ID

谢谢

【问题讨论】:

  • 尝试仅使用 1 个参数:.removeAttr('id') | api.jquery.com/removeAttr
  • $('div.panel-group').removeAttr('id'); 如果你有 2 个参数,你只是在设置
  • 不幸的是,这不起作用。我可以成功 $('#myID123').removeAttr('id');但我想搜索类名。
  • @RRowan 您需要指定要从使用更具体选择器的索引中删除 ID 的元素
  • @RRowan 能否提供 html 以便我们牢牢掌握手头的问题

标签: jquery attr


【解决方案1】:

试试这个。这将解释你想要什么。 尝试单击第一个 div,如果类名等于您的查找名称,它将删除该 div 的 id。然后它将删除所有样式,对于该 id。试试吧。希望这对你有帮助。

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
	
</head>

<style type="text/css">
div.container div{
	width: 100px;
	height: 100px;
	border:1px solid black;
	margin:20px;
	cursor: pointer;

}

.first{
	background-color: orange;
}

.second{
	background-color: pink;
}

.third{
	background-color: purple;
}

#firstid{
	border:10px solid red;
}

</style>

<body>
	
<div class="container">
	<div class="first" id="firstid">class = "first" and <br> id="firstid"</div>
	<div class="first" id="secondid">class = "first" and <br>id="secondid"</div>
	<div class="second" id="thirdid">class = "second" and <br>id="thirdid"</div>
	<div class="third" id="fourthid">class = "third" and <br>id="fourthid"</div>
</div>


</body>

<script type="text/javascript">
 $(document).ready(function()
 {
 	$("div.container div").click(function(){
 		var the_class = $(this).attr('class');//get the class name of clicked one
 		var the_id = $(this).attr('id');//get the id of the clicked

 		alert("The class name :"  +the_class + " and the id :"+the_id);

 		//then implment your condition
 		if (the_class == "first") 
 		{
 			$("[class='first']").removeAttr('id');
 		}



 	});
 	
 });


</script>
</html>

【讨论】:

    【解决方案2】:

    这个对我有用,我显示一个带有元素 ID 的警报并删除元素的 ID,然后如果我再次显示一个警报,则 ID 未定义。

    <div class="panel-group" id="test">
    First Div
    </div>
    <div class="panel-group" id="test2">
    Second Div
    </div>
    

    脚本:

    $('div.panel-group').each(function(){
                alert($(this).attr('id'));
          $(this).removeAttr('id');
          alert($(this).attr('id'));
    });
    

    还要检查 Jsfiddle:https://jsfiddle.net/f72q9wao/

    无论如何,请尝试分享一些 HTML,以便我们有更好的想法。

    【讨论】:

      猜你喜欢
      • 2018-03-14
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      相关资源
      最近更新 更多