簡體   English   中英

使用AJAX和jQuery .get()從外部文檔中檢索特定元素

[英]Retrieve specific element from external document using AJAX and jQuery .get()

使用ajax和jQuery,我試圖在用戶切換開關時從外部文檔中的特定元素加載內容。 目標內容由切換開關元素的name

所以我從HTML開始...

<input id="toggle1" name="externalContent1" class="toggle" type="checkbox">
<input id="toggle2" name="externalContent2" class="toggle" type="checkbox">
<input id="toggle3" name="externalContent3" class="toggle" type="checkbox">

我首先嘗試使用'.load()'...

$('.toggle').click(function () {

  var section = '#' + $(this).attr('name');

  if ($(this).is(':checked')) {
    $('#target').load("content.htm " + section);
  }

  else {
    $(section).remove();
  }
});

此方法有效,但是它將替換#target元素的內容。 我需要添加而不是替換。

所以然后我嘗試使用.get()從其他SO 問題中提出一些建議

if ($(this).is(':checked')) {
  var content;
  $.get('content.htm ' + section, function(data) {
    content = data;
    $('#target').append(content);
  });
}

但是這些使用.get() .post().ajax()解決方案(至少以我嘗試過的方式),不允許我在content.htm指定一個元素,它只是將整個文獻。

有沒有一種方法可以使用.get()從外部文檔中檢索特定元素?

正如我一直在思考的過程一樣,我想我也可以在檢索到的頁面中搜索該section ,並僅附加該部分。 我找到了這個建議 ,並嘗試了一下,但我對此也沒有任何運氣:

if ($(this).is(':checked')) {
  $.ajax({
    url: 'content.htm',
    type: 'GET',
    success: function(res) {
      $(res.responseText).find(section).each(function(){
        $('#target').append($(this).html());
      });
    }
  });
}

有了一點技巧,您就可以使用.load()解決方案。 首先加載到單獨的元素中,然后追加。

if ($(this).is(':checked')) {
    $('<div id="tempForLoad">').load("content.htm " + section, function(){
        $('#target').append($('#tempForLoad').html());
        $('#tempForLoad').remove();
    });
 }

暫無
暫無

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

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