Javascript 链接到 <select> id

标签 javascript php jquery html

我的问题是我在 prestashop(1.6.1.9) CMS 页面中工作,我不允许将任何脚本放入 cms 页面源代码中。(我没有为此使用 iframe,这不是解决方案)..

所以我有一个下拉菜单,下拉菜单中的每个链接都链接到某个页面。我想使用 java 脚本函数来执行此操作。

但是因为我无法像这个例子一样在页面上调用java脚本,

<select id="selectdrops" name="newurl"  onchange="menu_goto(this.form)  ">
    <option value="/index.html">Home</option>
    <option value="/feedback.html">Feedback</option>
    <option value="/links.html">Related Links</option>
</select>

如果可能的话,我希望让我的 JavaScript 集中在下拉菜单“ID”上?

删除:menu_goto(this.form) 我仍然希望通过关注选择的“ID”来完成目标链接。

我的 .js 看起来像这样:

$(document).ready(function () {

    $(document).on('change', '#dropSelectAbout', function (e) {
        e.preventDefault();
        menu_goto();
    });

    $(document).ready(function() {
        $("a").click(function(event) {
            alert(event.target.id);
        });
    }); 

});

function menu_goto( menuform )
{
   var baseurl = window.document.location.protocol + '//' + window.document.location.host;
   selecteditem = menuform.newurl.selectedIndex ;
   newurl = menuform.newurl.options[ selecteditem ].value ;
   if (newurl.length != 0) {
     location.href = baseurl + newurl ;
   }
}

最佳答案

我建议进行以下更改;

$(document).on('change', '#selectdrops', function (e) {
       e.preventDefault();
       menu_goto(e.target.value);
    });
})

function menu_goto( newurl ) {
    var baseurl = window.document.location.protocol + '//' + window.document.location.host;

    if (newurl.length != 0) {
        window.location = baseurl + newurl ;
    }
}

已删除:(下面的脚本已删除,因为它以页面上的所有 标记为目标,单击链接时会创建弹出对话框消息,因此顶部的功能仅需要专注于我的下拉列表的脚本,其中id=“selectdrops”)

    $(document).ready(function() {
        $("a").click(function(event) {
           alert(event.target.id);
        });
    });

e.target.value 将为您提供所选选项,因此您可以将该值直接传递到 menu_goto 函数中。
location 没有 ref 属性,因此如果打算重定向到新构造的 url,请使用 window.location

关于Javascript 链接到 <select> id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41804034/

相关文章:

Javascript 逻辑运算符和结果

php - 使用 GET 从编码 UTF-8 从 URL 获取值

php - 查询用户组隐藏搜索结果

javascript - Parse.FacebookUtils.logIn 是否只允许通过弹出框登录 Facebook?

javascript - OpenSSL加密后使用CryptoJS解密

javascript - 使用 css 设置后获取 Canvas 像素数据是错误的

javascript - 如何使用 JavaScript 使 Repeater 内的 TextArea 在单击按钮时显示?

jquery - 如何通过 jQuery 更新 cookie 的过期日期?

javascript - 下划线模板中的 "unexpected token <"

php - 定期更新表