簡體   English   中英

如何在jquery中結合兩個功能?

[英]How do I combine two functions in jquery?

如何結合這兩個功能並在updatePrice函數中通知var price 目前,我只能在第一個函數中提醒price ,但我想在updatePrice函數中調用alert(price)

$(document).ready(function()
{

var json = (function () {
var json = null;
$.ajax({
    'async': false,
    'global': false,
    'url': 'https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD',
    'dataType': "json",
    'success': function (data) {
        json = data[0].price_usd;
        var price = JSON.stringify(json);
        var price = JSON.parse(price);
        alert(price);
    }
});
})(); 

function updatePrice ()
{
    var ethprice = parseFloat($(".usd-input").val());
    var ethtotal = (ethprice) / 298;
    var ethtotal = ethtotal.toFixed(3);
    if(isNaN(ethtotal)) {
    var ethtotal = "";
    }
    $(".eth-input").val(ethtotal);

    var tvcprice = parseFloat($(".usd-input").val());
    var tvctotal = (tvcprice) / 1;
    var tvctotal = tvctotal.toFixed(3);
    if(isNaN(tvctotal)) {
    var tvctotal = "";
    }
    $(".tvc-input").val(tvctotal);
}
$(document).on("change, keyup", ".usd-input", updatePrice);  

})

將第一個函數(例如showAlert() )聲明為全局函數,然后從updatePrice()函數調用它。

並在全局范圍內聲明price變量,因為您要從updateFunction()函數訪問它。

var price;     // declare in global scope, so can be accessable from anywhere.

var showAlert = function () {
  var json = null;
  $.ajax({
    'async': false,
    'global': false,
    'url': 'https://api.coinmarketcap.com/v1/ticker/ethereum/?
     convert=USD',
     'dataType': "json",
     'success': function (data) {
      json = data[0].price_usd;
      price = JSON.stringify(json);
      price = JSON.parse(price);
      alert(price);
    }
  });
}

showAlert();

現在,只需從updatePrice()函數內部調用showAlert()即可

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM