通过div加载的页面中选择下拉菜单

3
我正在通过div加载一个页面,因为iframe有限制。我的目标是访问页面内容并选择下拉列表中的第一项。如果下拉列表的id叫做myDropdown或者像"ctl00_ctl65_g_549adf60_cb6b_4794_af15_99ce724b040f_FormControl0_V1_I1_D2"这样,我该如何访问它以进行选择?
$(document).ready(function() {
  $("#load_home").on("click", function() {
    $("#content").load("https://page.aspx");
  });
});

<div id="topBar">
  <a href="#" id="load_home"> Rate!</a>
</div>
<div id="content">
</div>

您在控制台中是否收到跨域错误?具体是哪个网页? - Neil
你好。请注意,在<html>标签之前,您正在加载jQuery版本1.11.1,然后再次加载旧版本的jQuery。 - Nick Gatzouli
那是由于片段编辑器的原因。 - mplungjan
你是否有一些尝试访问选择器但失败的JS代码?如果是,请发布它。 - Bango
这是一个sharepoint.aspx页面。没有错误。它已经加载。我只是想预先选择一个下拉菜单选项。 - Vzupo
3个回答

1
尝试这个脚本。
    var interval;
    $(document).ready(function () {
        $("#load_home").on("click", function () {
            $('.calc-loader').show();
            $("#content").load("HtmlPage5.html");

            interval = setInterval(function () {
                console.log($('#content select option').length);
                if ($('#content select option').length > 2) {
                    clearInterval(interval);
                    $('.calc-loader').hide();
                    $('#content select option:eq(3)').prop("selected",true);
                    $('#content select').trigger('change');
                }
            }, 1000);
        });
    });

为什么要将值设置为该值?只需像我的答案一样将选定项设置为true即可。 - mplungjan
我知道。那就是我建议的。 - mplungjan
我已经更新了最新的代码,使用了间隔函数,因为在.aspx页面上,下拉选项需要一些时间才能填充。同时触发更改事件,因为在选择更改后会执行一些代码。 - Vindhyachal Kumar
他在fiddle上分享了下拉代码 https://jsfiddle.net/v0nni/wumk46bs/。最初我的代码对他来说无法工作,所以我进行了修改,现在它可以正常运行了。 - Vindhyachal Kumar

0
你需要在.load回调函数或委托中访问它:
$(function() {
  $("#load_home").on("click", function() {
    $("#content").load("https://page.aspx",function() {
      $("#myDropdown option:eq(2)").prop{"selected",true);
      // if you have event handlers on the select, you want to trigger them
      $("#myDropdown").change(); 
    });
  });
});

委托:

$("#content").on("change","#myDropdown",function() {
  // delegated the change event to the container
});

需要以这种方式访问它吗,还是在加载时成为DOM的一部分,可以正常访问? - Bango
这是一个不完整的答案。OP没有指定选择框的id以及第一个选项的值。 - kind user
根据问题中提供的信息,我给出的示例已经涵盖了大多数情况。 - mplungjan

0
这是一个使用纯JS的模块化findAndSelect()函数。 参数是选择器的字符串ID和要选择的选项的字符串值。
假设你的html是:<select id="sel"><option>option1</option></select>,你想将#sel设置为'option1',则调用findAndSelect('sel','option1');
function findAndSelect (elementId, optionToSelect) {

  function findRelevantIndex(elementId) {
    var optionsArr = document.getElementById(elementId).options;
    var optionsLen = optionsArr.length;
    for (var i = 0; i < optionsLen; i++) {
      if (optionsArr[i].text == optionToSelect) {
        return i;
      }
    }
    console.log('found no matching option as ' + optionToSelect);
    return 0;
  }
  document.getElementById(elementId).selectedIndex = findRelevantIndex(elementId);
  console.log('new selected index for ' + elementId + ' is ' + document.getElementById(elementId).selectedIndex);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接