Jquery脚本只影响我页面中的第一个DIV? [英] Jquery script only affects first DIV in my page?
问题描述
我是jQuery的新手,似乎无法让以下代码符合我的喜好:
I am new in jQuery, and can't seem to get the following code to work to my liking:
<script type="text/javascript">
jQuery(document).ready(function($) {
$.fn.digits = function(text){
$(this).text(text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + '€' );
};
var tempText = $.trim($("#price").text());
tempText = tempText.substr(0, parseInt(tempText.length) );
$("#price").digits(tempText);
});
</script>
它应该将所有#price divs中的数字转换为逗号分隔的货币版本:
1000000 = 1,000,000€
这适用于页面上第一个#price实例,但如果相同的ID在同一页面上出现不止一次,其余的不是由脚本格式化的。
我发现DIV是唯一的,所以我试图改变然后代替类(#price到.price)这样做,但现在创造了一个新问题。现在.price的所有实例都显示在.price的每个实例中 - 如果这是有意义的。
假设我在一页中有3次.price 3次:
示例1(.price):200000
示例2(.price):250000
例3(.price):300000
应显示:
< br $>
200,000€
250,000€
300,000€
而不是它给了我:
200,000€250,000€300,000€
200,000€250,000€300,000€
200,000€250,000€300,000€
为什么是那个,我该如何解决?
谢谢!
我有什么试过:
It's should convert numbers in all #price divs in to comma seperated currency versions:
1000000 = 1,000,000€
This works fine for the fist instance of #price on a page, but if the same ID appears more than one time on the same page, the rest are not being formatted by the script.
I found out that DIV's mus be unique, so i tried to change then to classes in stead (#price to .price) which does the trick, but now creates a new problem. Now all instances of the .price are shown in every instance of the .price - if that makes sense.
Let's say i have .price 3 times in one page:
Example 1 (.price): 200000
Example 2 (.price): 250000
Example 3 (.price): 300000
Should show:
200,000€
250,000€
300,000€
In stead it gives me:
200,000€ 250,000€ 300,000€
200,000€ 250,000€ 300,000€
200,000€ 250,000€ 300,000€
Why is that, and how do i fix it?
Thanks!
What I have tried:
<pre><script type="text/javascript">
jQuery(document).ready(function($) {
$.fn.digits = function(text){
$(this).text(text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + '€' );
};
var tempText = $.trim($("#price").text());
tempText = tempText.substr(0, parseInt(tempText.length) );
$("#price").digits(tempText);
});
</script>
和(改为课程)
and (changed to classes)
<pre><script type="text/javascript">
jQuery(document).ready(function($) {
$.fn.digits = function(text){
$(this).text(text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + '€' );
};
var tempText = $.trim($(".price").text());
tempText = tempText.substr(0, parseInt(tempText.length) );
$(".price").digits(tempText);
});
</script>
推荐答案
){
.fn.digits = function(text){
.fn.digits = function(text){
(this).text(text.replace(/(\ d))(?=(\\\\)+(? !\d))/ g,
(this).text(text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "
这篇关于Jquery脚本只影响我页面中的第一个DIV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!