简体   繁体   English

如何在下拉菜单中调用javascript或jquery函数

[英]How to call javascript or jquery function inside dropdown

I have the following HTML code: 我有以下HTML代码:

<select name = 'category' id='category'>
    <option value="a">A <a href="" class = "edit" id ='1'> Click here to edit </a> </option>
    <option value="b">B <a href="" class = "edit" id ='b'> Click here to edit </a> </option>
</select> 

I am trying like this: 我正在这样尝试:

$(document).on('click','.edit', editfunction);

function editfunction() {
    alert('hi');
    //call here ajax code 
}

Firstly your HTML is invalid; 首先,您的HTML无效; you cannot have a elements inside an option : 您不能在option a元素:

<select name="category" id="category">
    <option value="a">A</option>
    <option value="b">B</option>
</select>

To do what you require you can hook to the change event of the select , not the click of the a within the option . 做你需要,你可以钩到什么change了的情况下select ,而不是click的的a的范围内option You can then use $(this).val() to get the selected value in editFunction() : 然后,您可以使用$(this).val()来获得在选定值editFunction()

$(document).on('change', '#category', editfunction);

function editfunction() {
    var value = $(this).val();
    console.log(value);
    // AJAX...
}

Try using the following 尝试使用以下内容

$('#category').on('change', function(){
   editfunction( $(this).val() );
 })

function editfunction(val){
   // Make your ajax call here
}

And You actually dont need the tag inside to make this happen 而且您实际上不需要内部的标签即可实现此目的

I think this is what u want JSFIDDLE example 我想这就是你想要的JSFIDDLE示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM