gpt4 book ai didi

javascript - 为什么这个 JavaScript 函数在网站首次加载时计算不正确,但之后可以正常工作?

转载 作者:行者123 更新时间:2023-11-30 17:21:28 25 4
gpt4 key购买 nike

我在一个网站上工作,该网站根据用户选择的一些参数为随机音乐节奏生成乐谱。它通过使用 ajax 调用来执行此操作,该调用返回一组随机的 <img>。代表不同音符的元素。我有一个功能,旨在缩放节奏以适合屏幕,而不管它的实际大小。

该函数在ajax调用成功后触发,该调用由按钮上的点击事件触发。

我的问题是该函数在第一次加载页面时运行时无法正常工作。

函数第一次运行后,height所有 <img> 的属性元素以某种方式设置为 0 .

但是,如果我再次运行它(通过单击按钮),该功能会很好用。它在页面刷新后也能正常工作。

此外,我在 IE11 中没有这个问题,只有 Chrome(我还没有测试过其他浏览器)。

我已经尝试将代码包装在 $(window).load() 中和 $(document).ready()事件处理程序,但这没有帮助。

可以在 http://www.rhythmrandomizer.com 找到正在运行的网站

如有任何帮助,我们将不胜感激!

相关代码如下:

按钮的事件处理程序:

$("#randomize").click(function(){
//get general options from form
var timeSignature = $("#timeSignature").val();
var phraseLength = $("#phraseLength").val();

//get note options from form
var checked = [];
$("#noteOptions :checked").each(function() {
checked.push($(this).val());
});

//alert user and exit function if nothing is selected
if (checked.length < 1) {
alert("Please select at least one note value");
return;
}


//format note option ids into a delimited string
var noteOptions = "";
for (var i=0; i < checked.length; i++) {
noteOptions += checked[i] + "a";
}

//remove the final comma and space
noteOptions = noteOptions.substr(0, noteOptions.length - 1);

//ajax call
$.ajax("randomize.php", {
data : {
timeSignature : timeSignature,
phraseLength : phraseLength,
noteOptions : noteOptions
},
type : "GET",
success : function(response) {
$("#rhythm").html(response);
scaleRhythm();
},
error : function(xhr, status, errorThrown) {
console.log(status + " | " + errorThrown);
}
});
});

返回节奏符号的 php 文件:

<?php
//MySQL connection variables
$hostname = 'localhost';
$user = ini_get('mysqli.default_user');
$pw = ini_get('mysqli.default_pw');
$database = 'rhytxfpd_rhythmrandomizer';

//Connect to database
try {
$db = new PDO('mysql:host=' . $hostname . ';dbname=' . $database,$user,$pw);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}

//Get values from GET
$timeSignature = $_GET['timeSignature'];
$phraseLength = $_GET['phraseLength'];
$noteOptString = $_GET['noteOptions'];

//Split up note options string
$noteOptions = explode('a', $noteOptString);

//Create sql query
$sql = 'SELECT
noteName,
noteValue,
noteGraphic
FROM
notes
WHERE';

//append noteOptions as WHERE clauses
foreach ($noteOptions as $opt) {
$sql = $sql . ' noteGroupID = ' . $opt . ' OR';
}

//remove final " OR"
$sql = substr($sql, 0, strlen($sql) - 3);

//query the database and get all results as an array
/* This will return a table with the name, graphic, and value of
* the notes that the user selected prior to submitting the form
*/
$stmt = $db->query($sql);
$result = $stmt->fetchAll();

//Get the total number of options selected
$numOpts = count($result);

/***************************/
/** BEGIN PRINTING RHYTHM **/
/***************************/

//div to begin the first measure
echo '<div class="measure" id="m1' . $measure . '">';

//Print time signature
echo '<img class="note" src="notes/' . $timeSignature . '.png" title="time signature ' .
$timeSignature . '/4" alt="time signature ' . $timeSignature . '/4"/>';

//Prints as many measures as indicated by the phrase length selection
$measure = 1;
while ($measure <= $phraseLength) {

//begin a new div for other measures.
if ($measure != 1) {
echo '<div class="measure" id="m' . $measure . '">';
}

//Prints random measure according to time signature
$beats = 0;
while ($beats < $timeSignature) {
//Generate a random number
$random = rand(0, $numOpts - 1);

//Get the random note from results
$note = $result[$random];

//Continues if chosen note will not fit in the measure
if ($beats + $note['noteValue'] > $timeSignature) {
continue;
}

//Prints random note
echo '<img class="note" src="notes/' . $note['noteGraphic'] . '.png" title="' .
$note['noteName'] . '" alt="' . $note['noteName'] . '"/>';

//Adds random note's value to total number of beats
$beats += $note['noteValue'];
//$beats++;
}

//If last measure
if ($measure == $phraseLength) {
echo '<img class="note" src="notes/1.png" title="double barline" alt="double barline"/>';
echo '</div>';
} else {
echo '<img class="note" src=notes/b.png title="barline" alt="barline"/>';
echo '</div>';
}

//Increment to next measure
$measure++;
}

scaleRhythm() 函数:

function scaleRhythm() {
//Get width of rhythm at full resolution
var rhythmWidth = $("#rhythm").width();

//Get current screen/window width
var screenWidth = window.innerWidth;

//Compute ratio between curren screen and window widths
var ratio = screenWidth / rhythmWidth;

//Multiply img note height by ratio, then by 90% to provide some
//breathing room on either side of the rhythm
var newHeight = (400 * ratio) * .9;

//Set img note height to new height or 300px, whichever is smaller
if (newHeight < 300) {
$(".note").css("height",newHeight);
//code to center rhythm horizontally
$("#rhythm").css("margin-top",(300-newHeight)/2);
} else {
$(".note").css("height",300);
$("#rhythm").css("margin-top",0);
}
}

最佳答案

将此 javascript 添加到您的 <script></script> :

$(function(){ $("#randomize").click(); });

这将使您的页面运行填充随机元素的函数,然后(在该函数的末尾)运行缩放函数。

我通过在 chrome 控制台中的页面上运行它来测试它并且它有效。

关于javascript - 为什么这个 JavaScript 函数在网站首次加载时计算不正确,但之后可以正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25067914/

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