gpt4 book ai didi

javascript - 通过从 html 对象 ID(例如按钮 ID)传递变量来合并 javascript 函数

转载 作者:行者123 更新时间:2023-11-28 10:50:29 27 4
gpt4 key购买 nike

尝试通过传递按钮本身的变量将这三个子函数合并为一个子函数。我目前有四个按钮,每个按钮都会触发主要功能。在主函数内部,我有三个子函数,它们使用三个新 html 变量之一更改 div 的内容。因此每个按钮都可以将 div 更改为其各自的内容。这段代码现在对我来说没有问题,但我认为必须有一种方法可以通过将 .replaceWith 设置为全局变量来将该子函数变成一个函数而不是三个。在函数内部,会有一个 getter 来检查被单击按钮的 ID,并将其传递给 ReplaceWith。

<script>
$(document).ready(function(){
$("button.first").click(function(){
$('div.switchMeOut').replaceWith(firstHTML);
});
$("button.second").click(function(){
$('div.switchMeOut').replaceWith(secondHTML);
});

$("button.third").click(function(){
$('div.switchMeOut').replaceWith(thirdhtml);
});

});
var firstHTML = '<div class="switchMeOut"><p>First Section Content</div>';
var secondHTML = '<div class="switchMeOut"><p>Second Section Content</div>';
var thirdHTML = '<div class="switchMeOut"><p>Third Section Content</div>';
</script>


<body>
<div id="parentblock">
<h5>Contacts List</h5>
<div class="switchMeOut">
<script> document.write (firstHTML + seconcHTML + thirdHTML); </script>
</div>
</div>

<button id="firstHTML" class="swapper first">Shows First Only </button>
<button id="seconcHTML" class="swapper second">Shows Second Only </button>
<button id="thirdHTML" class="swapper third">Shows Third Only </button>
</body>

所以这是我认为接下来应该做的事情,但我肯定错过了一些东西。

<script>
$(document).ready(function(){
$("button").click(function(){
// some code here to get the buttons ID element
// and possibly set a variable to that buttons id.
var passThis = button#;
$('div.switchMeOut').replaceWith(passThis);
});
});

然后让每个按钮都有自己的 id。例如:

<button id="firstHTML" class="swapper first">Shows First Only </button>

对此的任何帮助将不胜感激,我不太知道我在这里缺少什么,但我觉得它非常接近。

谢谢!

最佳答案

你可以像这样获取被点击元素的ID:

var passThis = $(this).attr("id");

但我认为你也需要这样做:

var htmls = {
firstHTML: '<div class="switchMeOut"><p>First Section Content</div>',
secondHTML: '<div class="switchMeOut"><p>Second Section Content</div>',
thirdHTML: '<div class="switchMeOut"><p>Third Section Content</div>'
}

然后你的切换语句将如下所示:

$('div.switchMeOut').replaceWith(htmls[passThis]);

关于您的评论:

htmls 不是一个数组,它是一个对象。它在 javascript 中被称为对象,但人们也称它们为字典、哈希、关联数组、键/值对等。请参阅:https://en.wikipedia.org/wiki/Associative_array

此外,您无法“调用”数组或对象。你调用一个函数。对于数组来说,最好的表达方式是“我检索/获取了索引 3 处的值”,对于对象来说是“我检索/获取了 firstHtml 属性”。

关于javascript - 通过从 html 对象 ID(例如按钮 ID)传递变量来合并 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34070150/

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