2014-06-30 29 views
0

我在我的應用程序中使用了導航欄。單擊導航欄元素時,我需要更改div中的圖像。我如何獲得div ID,以便我可以用另一個div替換相應的div?在jQuery中替換div的問題

 <div data-role="navbar"> 
     <ul> 
      <li><a id="test1" href="#">Test1</a></li> 
      <li><a id="test2" href="#">Test2</a></li> 
      <li><a id="test3" href="#">Test3</a></li> 
      <li><a id="test4" href="#">Test4</a></li> 

     </ul> 
    </div> 


     <div id= "SelectedData"> I need to replace this div on click event.</div> 

不同的圖像進行相應的點擊

 <div id="replaceData" style="width: 100%;"> 
      <img src="img/test1.jpg" alt="" style="width: 100% !important; height:15% !important"> 
     </div> 
<div id="replaceData1" style="width: 100%;"> 
      <img src="img/test2.jpg" alt="" style="width: 100% !important; height:15% !important"> 
     </div> 
<div id="replaceData2" style="width: 100%;"> 
      <img src="img/test3.jpg" alt="" style="width: 100% !important; height:15% !important"> 
     </div> 
<div id="replaceData3" style="width: 100%;"> 
      <img src="img/test4.jpg" alt="" style="width: 100% !important; height:15% !important"> 
     </div> 

腳本代碼:

$('div[data-role="navbar"] ul li a#test1').on('click', function() { 
      $('#replaceData').replaceWith($('#replaceData1').html()); 
     }); 
     $('div[data-role="navbar"] ul li a#test2').on('click', function() { 
      $('#replaceData').replaceWith($('#replaceData2').html()); 
     }); 
$('div[data-role="navbar"] ul li a#test3').on('click', function() { 
      $('#replaceData').replaceWith($('#replaceData3').html()); 
     }); 
     $('div[data-role="navbar"] ul li a#test4').on('click', function() { 
      $('#replaceData').replaceWith($('#replaceData4').html()); 
     }); 

如何獲得所選擇的DIV ID,因此,我將那格。

+0

請分享你的小提琴.. –

+0

你試過'.html()' –

+0

不,我該怎麼做 – Vinod

回答

2

看起來你想要做的是換出DIV內的HTML,而不是替換DIV本身。試試這個:

$('div[data-role="navbar"] ul li a#test1').on('click', function() { 
    $('#replaceData').html($('#replaceData1').html()); 
}); 
$('div[data-role="navbar"] ul li a#test2').on('click', function() { 
    $('#replaceData').html($('#replaceData2').html()); 
}); 
$('div[data-role="navbar"] ul li a#test3').on('click', function() { 
    $('#replaceData').html($('#replaceData3').html()); 
}); 
$('div[data-role="navbar"] ul li a#test4').on('click', function() { 
    $('#replaceData').html($('#replaceData4').html()); 
}); 
0

「我如何獲得所選擇的DIV ID,因此,我將那格。」

我不太清楚,如果這是你問什麼,但是,好了,在這裏你去:

$(document).on('click', '.some-class', function(){ 
    console.log($(this).attr('id')); 
}); 

正如你所看到的,我做了一些改動。首先,我選擇$(document)並添加選擇器作爲參數。這樣,您可以依靠.on()方法來捕獲動態生成的元素。然後,在函數中,我記錄了$(this)(通過this後jQuery返回的對象)的ID。當然,你現在可以存儲值:

$(document).on('click', '.some-class', function(){ 
    var id = $(this).attr('id'); 
}); 

PS:

記住,你可以直接選擇標識。他們是獨特的,不需要太具體。除非你想加快速度與.find()

$(document).on('click', '#test1', function(){ 
    // your clever code! 
}); 

它的方式清潔閱讀而不是痛苦的希望寫成$('div[data-role="navbar"] ul li a#test1') :)

,這就是你想知道什麼。乾杯!