0

很抱歉,我发现我做错了.. 只是 html 文件和 txt 文件之间的典型错误

首先,我向我糟糕的英语道歉。

我正在尝试div通过jQuery通过ajax动态获取外部txt文件中的html代码。但是,我无法div按预期获得具体的 html 代码。这是我的代码

.html 文件

<div id="html_div_id_A">
  <div class="html_div_class">
  </div>  
</div>

<div id="html_div_id_B">
  <div class="html_div_class"> 
  </div>  
</div>

abc.txt 文件

<div id = "txt_div_id_A">
  <div class="txt_div_class">
        some content A
  </div>  
</div>

<div id = "txt_div_id_B">
  <div class="txt_div_class">
        some content B
  </div>  
</div>

.js 文件

function func(arg)
{
    var htmlDivId = $(arg).attr("id").toString()// html_div_id_A or html_div_id_B, decided in run time
    var txtDivId = htmlDivId == "html_div_id_A" ? "#txt_div_id_A" : "#txt_div_id_B";// txt_div_id_A or txt_div_id_B, decided in run time

    // What I could do now
    $(htmlDivId + " > .html_div_class").load("abc.txt #txt_id_B div");

    // What I expected to do
    $(htmlDivId + " > .html_div_class").load("abc.txt " + txtDivId + " div");
}

我已经尝试过这里建议的解决方案(在 $.AJAX 加载的 HTML 上使用 Jquery 选择器?),但它不起作用。有没有办法解决这个问题?

4

1 回答 1

0

尝试

function func(arg)
{
    var htmlDivId = $(arg).attr("id");

    //You need to assign the string value of the target id
    var txtDivId = htmlDivId == "html_div_id_A" ? 'txt_div_id_A' : 'txt_div_id_B';// txt_div_id_A or txt_div_id_B, decided in run time

    // What I expected to do
    // need to prepend # to target id
    $('#' + htmlDivId + " > .html_div_class").load("abc.txt #" + txtDivId + " div");
}

演示:Plunker

于 2013-06-18T06:01:00.263 回答