簡體   English   中英

更改元素的ID不適用於jQuery

[英]Changing the ID for an element doesn't work with jQuery

我想使用jQuery更改元素的ID( <div> )。 以下是我的JavaScript,CSS和HTML的示例。 現在,當我單擊<div> ,什么都沒有發生。

 $( ".pre_div" ).click(function() { $( ".pre_div" ).attr('id','after_div'); }); $( ".after_div" ).click(function() { $( ".after_div" ).attr('id','pre_div'); }); 
 #pre_div {width:20px;height:20px;background-color:red;cursor:pointer;} #after_div{width:20px;height:20px;background-color:blue;cursor:pointer;} 
 <div id="pre_div">:-)</div> 

您應該使用# – id選擇器–代替. –類選擇器(也可以使用this來訪問事件監聽器中的元素):

$( "#pre_div" ).click(function() { 
  $(this).attr('id','after_div');
});
$( "#after_div" ).click(function() { 
  $(this).attr('id','pre_div');
});

JSFiddle

請使用$(this)引用被單擊的項目,否則您可以給許多項目提供相同的id 但是,使用這種方法,您仍會將相同的ID輔助到每個單擊的div,這不好。 如何添加單擊的divindex以使其具有唯一 id

$(".pre_div").click(function() { //any div with pre_div class
  $(this).attr('id'+ $(this).index(),'after_div');
});
$(".after_div").click(function() { //any div with after_div class
  $(this).attr('id'+ $(this).index(),'pre_div');
});

. 是用於類,而#是用於id,加上您必須使用.on()函數,否則它將無法正常工作

$(document).on('click','#pre_div',function() { 
  $(this).attr('id','after_div');
});

$(document).on('click','#after_div',function() { 
  $(this).attr('id','pre_div');
});

JSFIDDLE演示

“ pre_div”和“ after_div”不是類,它們是您的div的ID

應該以這種方式訪問​​它。

$( "#pre_div" ).click(function() { 
  $( "#pre_div" ).attr('id','after_div');
});
$( "#after_div" ).click(function() { 
  $( "#after_div" ).attr('id','pre_div');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM