如何知道选择框中的可用选项何时更改

时间:2015-07-27 05:50:45

标签: javascript jquery html javascript-events

我的页面上有一个选项框,选项会动态更改。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 if (selectedTag==1) {
    selectedIndex=indexPath.row;
    [self performSelector:@selector(Write Your Action) withObject:nil];
}
NSMutableArray *modifiedRows = [NSMutableArray array];
if ([indexPath isEqual:self.expandedIndexPath]) {
    [modifiedRows addObject:self.expandedIndexPath];
    self.expandedIndexPath = nil;
}
else {
    if (self.expandedIndexPath)
        [modifiedRows addObject:self.expandedIndexPath];
        self.expandedIndexPath = indexPath;
        [modifiedRows addObject:indexPath];
}
// This will animate updating the row sizes
[tableView reloadRowsAtIndexPaths:modifiedRows withRowAnimation:UITableViewRowAnimationAutomatic];
// Preserve the deselection animation (if desired)
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
[tableView deselectRowAtIndexPath:indexPath animated:YES];


} 

当它发生变化时,我想根据显示的选项在屏幕上的其他地方刷新一些文字。

问题是我似乎找不到添加或删除选项时引发的事件。

如果选择框中的选项数量发生变化,我将如何收到通知。

1 个答案:

答案 0 :(得分:3)

您可以使用MutationObserver观看select元素以更改其内容:

var ob = new MutationObserver(function() {
  snippet.log("Changed");
});
ob.observe(document.getElementById("foo"), {
  subtree: true,
  childList: true
});
setTimeout(function() {
  document.getElementById("foo").options.add(new Option("Hi"));
}, 100);
<select id="foo"></select>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

MutationObserverwell-supported,但IE除外,它直到IE11才得到它们。但IE支持old mutation events;您可以找到使用旧事件提供新界面的填充/填充(或者只在typeof MutationObserver === "undefined"时直接使用旧事件)。我不知道当您更改选项中的选项时IE是否触发了旧事件,但是,您需要检查。

如果没有MutationObserver并且突变事件不起作用,则作为最后的手段,轮询。每50分钟左右轮询不应对页面的性能产生任何重大影响。