javascript - 如何使用 .click 函数从 div 中为变量提供字符串

标签 javascript jquery

潜伏了一段时间,虽然找不到解决这个问题的方法,所以如果这是转贴,请原谅, 问题是,我想让我的 <'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>

jsFiddle here.

关于javascript - 如何使用 .click 函数从 div 中为变量提供字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17135065/

相关文章:

javascript - 面膜不起作用?

javascript - 无法获得在华氏温度和摄氏温度之间切换的按钮

jquery - 时间选择器自动打开

javascript - 与innerText类似的行为,但保留 <img> 标签

javascript - 在 JS 中给字典键加上引号

javascript - 如何使用 Javascript/jQuery (Ajax) 检索 Google QPX 结果?

javascript - 解析从 jQuery AJAX 请求返回的 HTML

javascript - 在 Meteor 中添加对象后添加可调整大小的 JQuery UI

javascript - typescript如何实现枚举?

javascript - 如何在没有按钮的情况下激活 Toast