-3

我有这段代码用于获取所有链接并在新选项卡中打开它。

    var OptionBarSelector = "div.tCenter";
    var button = "<input id='allTabs' type='button' class='bold' style='width: 140px;'value='open all in new tab'/>";
    var host = "http://rutracker.org/forum";
    var tableId = "tor-tbl";
    var rowHref = ".tCenter.hl-tr td.row4.t-title a";  
$(function(){

    console.log("Rutracker search results in All Tab loaded");
    $(OptionBarSelector).append(button);  

    $("#allTabs").on('click',function(){

      $("#"+tableId+" tr"+rowHref).each(function(index,item){
          var link = host + $(this).attr("href").substr(1);
          window.open(link,"_newTab");     
    });
    });
});

html:

<td class="row4 med tLeft t-title" style="max-width: 669px;">
        <div class="wbr t-title" style="max-width: 669px;">
                        <a data-topic_id="534143" class="med tLink hl-tags bold" href="./viewtopic.php?t=534143">Text<span class="brackets-pair">[2001-2013, PDF, RUS]</span>Text 2</a>
        </div>
        <div id="tg-534143" class="t-tags"><span class="tg">Journal</span></div>
    </td>

但只打开第一个链接。如何解决?我想保持当前标签处于活动状态。

更新 我更改了代码,但现在此代码仅在新选项卡中打开第一个链接,另一个在弹出窗口中打开。如何在新标签而不是弹出窗口中打开其他链接?

    var OptionBarSelector = "div.tCenter";
    var button = "<input target='_blank' id='allTabs' type='button' class='bold' style='width: 140px;'value='open all in new tab'/>";
    var host = "http://rutracker.org/forum";
    var tableId = "tor-tbl";
    var rowHref = ".tCenter.hl-tr td.row4.t-title a";  
$(function(){
    $(OptionBarSelector).append(button);

    var allLinks = new Array();
       $("#"+tableId+" tr"+rowHref).each(function(index,item){
          var link = host + $(this).attr("href").substr(1);
          allLinks.push(link);
    });
    var varAllOpen = "";    
    for(var i = 0; i < allLinks.length; i++)
    {
        varAllOpen += "window.open('"+allLinks[i]+"','"+i+"');";
    }   
    console.log(varAllOpen);
    $("#allTabs").attr("onclick",varAllOpen);
    console.log("Rutracker search results in All Tab loaded");
});
4

1 回答 1

1

您的代码中有相当多的可疑 JS,但主要问题是您正在构建一个字符串,然后像执行函数一样执行它。不要解决不存在的问题:如果您希望函数在点击时触发,请将函数绑定到点击事件:

$(function(){
  $(OptionBarSelector).append(button);

  var links = [];      // don't use new Array()

  $("#"+tableId+" tr"+rowHref).each(function() {
    links.push(host + this.href.substring(1));
  });

  // actually bind a click handler function,
  // don't use strings attributes
  $("#allTabs").click(function() {
    links.forEach(function(link) {
      window.open(link);
    });
  });
});
于 2013-06-11T01:53:45.243 回答