在使用GreaseMonkey和"tamtam“编写jQuery脚本时,我脑海中出现了一个问题。
有一个有四个选项的<select>元素的页面(我无法编辑)。备选案文2是预选的。
<select id="idname" name="namename">
<option>Option1</option>
<option selected="selected">Option2</option>
<option>Option3</option>
<option>Option4</option>
</select>现在,当选择Option1时,我想调用这个脚本。Option1通向另一个站点,我想插入我的脚本。
我怎么写这样的东西:
if (Option1 is selected) {
perform the script
}像下面这样的东西会起作用吗?
if(document.getElementById("idname").getElementsByTagName("option")[0].onselect == true){
perform the script
}如果没有,你能给我发个推荐信吗?
编辑
我能够创建一个函数和一个事件处理程序。
function myCompute(Event) {
with (this) {
var myTest = value;
if (value == "option1") {
$("#tabelle").show();
}
else {
$("#tabelle").hide();
}
}
}事件处理程序:
$("#option-type").change (myCompute);
$("#tabelle").hide();它的工作方式如下:通过选择选项2、3或4,表是隐藏的。通过选择选项1,将显示该表。通过访问站点,大多数时间都会选择选项2,而不会显示任何内容。现在我看到的情况是,选项1是通过访问站点来选择的,并且没有出现任何表。我的想法是,当预选option1时,表应该显示。我想EventHandler不见了。就像你布罗克·亚当斯说的。
$("#option-type option:first").select (myCompute);
$("#option-type").change (myCompute);
$("#tabelle").hide();如果我用$("#tabelle").hide();绑定函数,表从一开始就被隐藏起来。通过将选项更改为option1,将显示表。选择选项1时如何显示表,选择选项2、3、4时如何隐藏该表?
尝试option:first会导致“未知伪元素”错误。
发布于 2010-07-05 18:53:37
更新:
好的,如果我理解修改后的问题,代码现在按照预期工作,除非选项1以选定的方式开始。(PS,应该编辑给定代码的id以匹配。)
如果这是真的,那么只需更改这一行:
$("#tabelle").hide();。
对此:
if ($("#option-type")[0].selectedIndex == 0 )
$("#tabelle").show();
else
$("#tabelle").hide();在Greasemonkey中,由于沙箱保护,您不能这样设置事件处理程序。见Greasemonkey中常见的陷阱。
此外,对于jQuery,有更容易的方法来选择该元素。
类似于:$("#idname option:first").select (YourEventHandler)应该能工作。
其中:
function YourEventHandler (Event)
{
//YOUR CODE HERE
//Note: Event is a variable passed automatically to all event handlers, you often just ignore it.
}方便的jQuery参考。
发布于 2010-07-05 12:08:10
您可以使用属性来获取所选的内容,如下所示:
if(document.getElementById("idname").selectedIndex === 0) { //option 1
//perform the script
}它是一个基于0的索引,所以在示例标记你可以在这里测试/玩它中0就是你可以在这里测试/玩它。
从这个问题上我不太清楚,但是如果您想在change事件中这样做,它应该是这样的:
document.getElementById("idname").onchange = function() {
if(this.selectedIndex === 0) {
//perform the script
}
};你不能在这里测试。
https://stackoverflow.com/questions/3179319
复制相似问题