简体   繁体   English

在新的div中克隆或追加变量?

[英]clone or append a variable in a new div?

I have this Html <h1 class="count" role="status">Search results 546</h1> 我有这个HTML <h1 class="count" role="status">Search results 546</h1>

I'm trying to clone only the numerical '546' of that div and display it inside another div 'h2.count' 我正在尝试仅克隆该div的数字'546'并将其显示在另一个div'h2.count'内

I manage to call only the numerical value in an alert via: 我设法通过以下方式仅调用警报中的数值:

var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
     alert(parsedPrice.toFixed(0));

Otherwise , when i try to make it display in the div h2.count instead of an alert, it is not working. 否则,当我尝试使其显示在div h2.count中而不是警报中时,它将不起作用。

I have try the below: 我尝试以下方法:

var price = $('h1.count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$parsedPrice.appendTo('h2.onlycount');

Any thought of what i am doing wrong ? 有想到我做错了什么吗?

Thanks a lot guys ! 非常感谢你们!

I guess that your two html elements are unique so, using id's instead of classes (and native js), try this : 我猜您的两个html元素是唯一的,因此,使用id代替类(和本机js),请尝试以下操作:

html : html:

<h1 id="count">Search results 541</h1>
<h2 id="onlycount"></h2>

js : js:

var price = document.getElementById('count').innerText;
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
document.getElementById('onlycount').innerText = parsedPrice;

https://jsfiddle.net/f3rj2bnv/ https://jsfiddle.net/f3rj2bnv/

And if you want to keep on using jQuery (replace "#" with "." if you want or have to use classes instead of ids in your html elements) : 而且,如果您想继续使用jQuery(如果希望或必须在HTML元素中使用类而不是ID的话,请将“#”替换为“。”):

var price = $('h1#count').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
$('h2#onlycount').text(parsedPrice)

The content used by .appendTo() should be .appendTo()使用的内容应为

"a selector expression or as markup created on the fly" “选择器表达式或动态创建的标记”

Since in your example neither is true, try this: 由于在您的示例中都不是正确的,请尝试以下操作:

 var price = $('h1.count').text(); var parsedPrice = parseFloat(price.replace(/([^0-9\\.])/g, '')); $('h2.onlycount').text(parsedPrice); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 class="count" role="status">Search results 546</h1> <h2 class="onlycount" role="status"></h1> 

Can use text(function) 可以使用text(function)

 $('h2.onlycount').text(function(_, existingText){ return existingText + $('h1.count').text().replace(/([^0-9\\.])/g, ''); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 class="count" role="status">Search results 546</h1> <h2 class="onlycount"></h2> 

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

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