gpt4 book ai didi

javascript - 单击按钮时执行 javascript 脚本

转载 作者:行者123 更新时间:2023-12-03 10:58:46 27 4
gpt4 key购买 nike

我正在使用 Google 驱动器选择器

问题是它会自动加载,当我只希望选择器在单击按钮而不是页面加载时出现。

在正文中,这是加载选择器的脚本

  <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>

我只想在单击按钮时执行此脚本。完整代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Picker Example</title>

<script type="text/javascript">

// The Browser API key obtained from the Google Developers Console.
var developerKey = 'xxxxxxxYYYYYYYY-12345678';

// The Client ID obtained from the Google Developers Console. Replace with your own Client ID.
var clientId = "1234567890-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com"

// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];

var pickerApiLoaded = false;
var oauthToken;

// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}

function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}

function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}

function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}

// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
addView(google.picker.ViewId.PHOTOS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}

// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'You picked: ' + url;
document.getElementById('result').innerHTML = message;
}
</script>
</head>
<body>
<div id="result"></div>

<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>

最佳答案

您可以尝试使用getScript来自 jQuery 的方法。它非常简单,将在单击事件期间加载文件。

$( '#button' ).on( 'click', function() {
$.getScript( 'url to your js file', function( data, textStatus, jqxhr ) {
// do some stuff after script is loaded
} );
} );

关于javascript - 单击按钮时执行 javascript 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28175728/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com