Javascript jQuery:如何处理跨度的更改文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10958529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery : How to handle change text of span
提问by Arian
I'm using jQuery and I want to show some calcution in a span (called span1
) and I want when text of span1
changed do some calcution on it's value and show in other spans(called `span2 ,span3,...). How I can handle text change of span?
我正在使用 jQuery,我想在一个跨度(称为span1
)中显示一些计算,我希望当span1
更改的文本对其值进行一些计算并在其他跨度中显示(称为 `span2 ,span3,...)。我如何处理跨度的文本更改?
thanks
谢谢
采纳答案by SpYk3HH
You could use the function that changes the text of span1 to change the text of the others.
您可以使用更改 span1 文本的函数来更改其他文本。
As a work around, if you really want it to have a change
event, then don't asign text to span 1. Instead asign an input variable in jQuery, write a change event to it, and whever ur changing the text of span1 .. instead change the value of your input variable, thus firing change event, like so:
作为一种解决方法,如果您真的希望它有一个change
事件,那么不要将文本分配到跨度 1。而是在 jQuery 中分配一个输入变量,向它写入一个更改事件,并且无论您更改 span1 的文本..而是更改输入变量的值,从而触发更改事件,如下所示:
var spanChange = $("<input />");
function someFuncToCalculateAndSetTextForSpan1() {
// do work
spanChange.val($newText).change();
};
$(function() {
spanChange.change(function(e) {
var $val = $(this).val(),
$newVal = some*calc-$val;
$("#span1").text($val);
$("#spanWhatever").text($newVal);
});
});
Though I really feel this "work-around", while useful in some aspects of creating a simple change event, is very overextended, and you'd best be making the changes to other spans at the same time you change span1.
虽然我真的觉得这种“变通办法”虽然在创建简单更改事件的某些方面很有用,但它的范围非常广,而且您最好在更改 span1 的同时对其他跨度进行更改。
回答by Ruchit Patel
Span does not have 'change' event by default. But you can add this event manually.
默认情况下,Span 没有 'change' 事件。但是您可以手动添加此事件。
Listen to the change event of span.
监听span的change事件。
$("#span1").on('change',function(){
//Do calculation and change value of other span2,span3 here
$("#span2").text('calculated value');
});
And wherever you change the text in span1. Trigger the change event manually.
无论您在什么地方更改 span1 中的文本。手动触发更改事件。
$("#span1").text('test').trigger('change');