简体   繁体   English

使用jquery和.change()选择html元素ID

[英]select html element id using jquery and .change()

I have several <select> boxes all using the same prefix and I would like to set up a recursive function to essentially do the work for me. 我有几个<select>框都使用相同的前缀,我想设置一个递归函数来为我做这些工作。

$('[id^="by_"]').change(function(e)
            {
                var elem = e;
                console.log(e.value);
            });

Based on this code is my intention pretty clear? 基于此代码,我的意图很明确吗? Am I on the right track? 我在正确的轨道上吗?

console prints out: undefined 控制台输出: undefined

I think you're on the right track - the selector you're using matches a prefix of "by_", and you're binding the change event to all of them. 我认为您处在正确的轨道上-您使用的选择器匹配前缀“ by_”,并且您将change事件绑定到所有这些事件。 Make sure you put this in $(document).ready or similar. 确保将其放在$(document).ready或类似$(document).ready Are you having any problems with this code? 这段代码有问题吗? Instead of using the e parameter, I would just use this inside of the function to refer to the element and $(this) to get the jQuery object of it. 而不是使用e参数,我只是在函数内部使用this来引用元素,并使用$(this)来获取它的jQuery对象。 So to get the value, you'd use: 因此,要获得价值,您可以使用:

this.value
// or
$(this).val()

(ignore the e and elem stuff, although it wouldn't be a bad idea to store $(this) in something like elem so you can have a reference to it instead of re-creating the jQuery object every time you need it) (忽略eelem东西,尽管将$(this)存储在elem这样的东西中并不是一个坏主意,因此您可以对其进行引用,而不是每次需要时都重新创建jQuery对象。

When using callbacks to events with jQuery, the (first) parameter of the callback is an event object that explains many things about the event that occurred ( http://api.jquery.com/category/events/event-object/ ) and does not hold the element - that's what this is for! 当通过jQuery使用事件的回调时,回调的(第一个)参数是一个event对象,它解释有关发生的事件的许多事情( http://api.jquery.com/category/events/event-object/ )和不包含元素- this就是它的作用!

e in your code is the event object which has no value property, you should use this instead: 代码中的e是没有value属性的事件对象,您应该改用this

$('[id^="by_"]').change(function(e) {
     var elem = this;
     console.log(this.value);
});

Or if you want to use event object, you can use target property: 或者,如果要使用event对象,则可以使用target属性:

e.target.value

Since you're already using jQuery, why not something like this: 由于您已经在使用jQuery,为什么不这样做呢?

$('[id^="by_"]').change(function(e)
{
    var $elem = $( this );
    console.log( $elem.val() );
});

Isn't it more something like that: 难道不是这样的吗?

$('[id^="by_"]').change(function()
            {
                console.log($('option:selected',this).val());
            });
​

jsfiddle jsfiddle

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

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