潜伏了一段时间,虽然找不到解决这个问题的方法,所以如果这是转贴,请原谅, 问题是,我想让我的 <'div> 可以点击,当我点击它时,它们返回 <'p> 内的字符串并将其分配给我的 Jscript 中的变量。 尝试了几种方法..我真的需要帮助!
这是我的 JS 代码:
var userChoice = $('div#select').click(function(){
$(this).effect('highlight' , { color: "rgba(36,117,203,0.6)" } , 'slow' , 500);
userChoice = (this,'<div id="select"></div>');
alert("Your choice:" + " " + userChoice);
});
这是 html :
<div class="rps"><p>Play Rock Scissors Paper!</p>
<div id="select"><p>rock</p></div>
<div id="select"><p>paper</p></div>
<div id="select"><p>scissors</p></div>
<div id="result"><p>result:</p></div>
</div>
最佳答案
使用类而不是重复的 ID,并在 jQuery 函数中使用 $(this).text()
(如果每个 div 中还有其他元素,您可以使用 .children(' p')
或 .find('p')
代替):
$('.select').click(function(){
$(this).effect('highlight' , { color: "rgba(36,117,203,0.6)" } , 'slow' , 500);
$('#result').text('result: ' + $(this).text());
});
将您的 HTML 作为:
<div class="rps"><p>Play Rock Scissors Paper!</p>
<div class="select"><p>rock</p></div>
<div class="select"><p>paper</p></div>
<div class="select"><p>scissors</p></div>
<div id="result"><p>result:</p></div>
</div>
关于javascript - 如何使用 .click 函数从 div 中为变量提供字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17135065/