你能在 jQuery 中扩展 val() 函数吗?
有没有办法扩展 jQuery 中的 val() 函数。
基本上,我想要做的是如果有内容被动态输入到输入中,则设置一个类变量。
Whick 通常会是这样的:
var thisVal = 'Hello World';
$('#myInput').val(thisVal).addClass('dark');
如果有值,告诉 val() 函数总是将“dark”类添加到输入中,如果为空则将其删除,这将是很好的选择。
可能的?
Is there a way to extend the val() function in jQuery.
Basically, what I want to do is set a class variable if there is content being dynamically entered into an input.
Whick normally would be something like
var thisVal = 'Hello World';
$('#myInput').val(thisVal).addClass('dark');
It would just be nice to tell the val() function to always add the class 'dark' to an input if there is a value, and to remove it if it is empty.
Possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
演示:http://jsfiddle.net/mattball/v9YFu/
Try
Demo: http://jsfiddle.net/mattball/v9YFu/
您可以这样做:
但我强烈建议您不要使用它,因为设置元素的值与设置 CSS 属性无关。
val
设置值,仅此而已。您可以做的是:每当以编程方式或由用户更改值时,都会调用您传递给更改的函数(请参阅文档)。这样,代码就变得更具可读性和可理解性,也使得调试变得更容易。
You could do this:
But I'd strongly discourage you to use it because setting an element's value has nothing to do with setting CSS properties.
val
sets values, and that's it. What you could do is this:The function you pass to change will be called, whenever the value is changed - programmatically or by the user (see documentation). This way the code gets much more readable and comprehensible, what makes it easier to debug too.
正如其他答案所指出的,您可以扩展(覆盖) val() 函数,但将不相关的行为硬编码到其中并不是一个好的做法。
但是,我发现以编程方式更改值时触发某些内容的一种方便方法是覆盖 val() 函数并触发元素的更改事件 - 但仅当该元素指定时。
您可以通过向元素添加数据属性(或类等)来定义该请求,如下所示:
然后,您的新 val 函数可以检查该属性。
...然后你可以编写一个更改处理程序来执行你喜欢的任何操作:
警告! 显然,如果您使用 val() 更改更改处理程序中的值,这样做可能会导致无限循环。如果你确实需要,你可以通过使用 $('input.dark-when-changed')[0].value = 'blah'; 来避免这种情况。
As pointed out by other answers, you can extend (overwrite) the val() function but it's not good practice to hardcode unrelated behaviour into it.
However, I find that a handy way of triggering something when the value is changed programatically is to overwrite the val() function and trigger the change event of your element - BUT ONLY IF SPECIFIED by that element.
You can define that request by adding a data attribute (or class etc.) to your element like so:
Then, your new val function can check for that attribute.
...and then you can write a change handler to do whatever you like:
WARNING! Doing this can result in an infinite loop if you change the value in your change handler using val(), obviously. If you really needed to, you could avoid that by using $('input.dark-when-changed')[0].value = 'blah';