简体   繁体   English

jQuery:从html元素获取数字并在Jquery / Javascript中对其进行更改

[英]JQuery: Getting number from html element and alter it in Jquery/Javascript

I have some number printed on my html for special usage, therefore i need to grab it from html, alter it in javascript and output again. 我在html上印有一些数字以作特殊用途,因此我需要从html抓取它,在javascript中对其进行更改,然后再次输出。

So i have few numbers like below in my HTML: 所以我的HTML中没有几个像下面这样的数字:

<p id="usage">6564</p> 

and i'd like to have a if statment in order do some modifcation of "6564", below is some pseudo codes, which tells what i'd like to do. 我想有一个if语句以便对“ 6564”进行一些修改,下面是一些伪代码,这些伪代码可以告诉我我想做什么。

var checker = $("#usage").html();

if(checker >= 2 digits){
  //display the first two digits 
}
else {
  $("#usage").html("1");
}

The if statement should display the first two digits only, if the number has more than 2 digits otherwise it will return "10" , So the result should be "65" 如果数字大于2,则if语句应仅显示前两位数字,否则将返回“ 10” ,因此结果应为“ 65”

Solution : 解决方案:

For people who experience the same issues as me 对于遇到与我相同问题的人

var checker = $(".totalPage").text().replace(/,/g, ""); //it you have comma between your number like 6,545
var pagevalue = parseInt(checker.slice(0,2));

        if(checker.length >= 2){
          $(".totalPage").text(pagevalue+1);//you can modify the our put even further 
        }
        else {
          $(".totalPage").text("10");
        }

 var checker = $("#usage").text(); if(checker.length >= 2){ $("#usage").text(checker.slice(0,2)); } else { $("#usage").text("10"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="usage">6564</p> 

  1. Use slice to get the 2 digits. 使用slice获取2位数字。
  2. Use length to tell if number has more than 2 digits 使用长度来判断数字是否超过2位数字

Here's the pure Js version. 这是纯Js版本。

 function extractFunction() { var checker = document.getElementById("usage").innerHTML; if (checker.length > 2) { //if cheacker lentgh > 2 var result = checker.substr(0, 2); //start at char 1 and pull first 2 chars document.getElementById("usage").innerHTML = result; } else{ document.getElementById("usage").innerHTML = "1"; } } 
 <p id="usage">6564</p> <button onclick="extractFunction()">Extract it</button> 

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

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