简体   繁体   English

当存在多个相等的CSS类时,使用jQuery val()获得正确的值

[英]Getting the right value with jQuery val() when there are multiple equal css classes

I have a code as follows. 我有如下代码。

I need to get the name of the user whos button has been clicked. 我需要获取已单击的用户whos按钮的名称。 This example has to be fixed because there are several "user_name" classes and I think jQuery doesn't know what value to grab with val(). 该示例必须修复,因为有几个“ user_name”类,而且我认为jQuery不知道使用val()可以获取什么值。

How can I fix this? 我怎样才能解决这个问题?

 $(document).ready(function(){ $(document).on("click", ".btn" , function() { var myuser = $('user_name').val(); }); }); 
 <div id="message_box"> <div> <span class="user_name"> <button class="btn">Click</button> John </span>: <span class="user_message">Hello!</span> </div> <div> <span class="user_name"> <button class="btn">Click</button> Jeff </span>: <span class="user_message">Hi!</span> </div> <div> <span class="user_name"> <button class="btn">Click</button> Jane </span>: <span class="user_message">Whats up?!</span> </div> </div> 

You need to use traversal methods: 您需要使用遍历方法:

 $(document).ready(function(){ $(document).on("click", ".btn" , function(e) { e.preventDefault(); var myuser = $(this).closest('div').find('.user_name').text(); console.log(myuser); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="message_box"> <div> <button class="btn">Click</button> <span class="user_name">John</span>: <span class="user_message">Hello!</span> </div> <div> <button class="btn">Click</button> <span class="user_name">Jeff</span>: <span class="user_message">Hi!</span> </div> <div> <button class="btn">Click</button> <span class="user_name">Jane</span>: <span class="user_message">Whats up?!</span> </div> </div> 

Note how I've moved the button out of the span so that its text is not included in the result. 注意如何将按钮移出范围,以便其文本不包含在结果中。 Alternatively, you could use an input: 另外,您可以使用输入:

<input class="btn" type="button" value="Click" />

Just modify the HTML as below since it would be feasible for us to traverse to the relevant element and try to use the this context to retrieve the value relative to the clicked button, 只需按如下所示修改HTML,因为我们可以遍历相关元素并尝试使用this上下文来获取相对于所单击按钮的值,

HTML: HTML:

<div id="message_box">
    <div>
        <button class="btn">Click</button><span class="user_name"> John</span>: <span class="user_message">Hello!</span>
    </div>
    <div>
        <button class="btn">Click</button><span class="user_name"> Jeff</span>: <span class="user_message">Hi!</span>
    </div>
    <div>
        <button class="btn">Click</button> <span class="user_name">Jane</span>: <span class="user_message">Whats up?!</span>
    </div>
</div>

JS: JS:

$(document).ready(function(){
  $(document).on("click", ".btn" , function() {
    var myuser = $(this).next('.user_name').val();
  });
});

DEMO 演示

You need to add type="button" to the button to prevent default action of submitting, because buttons with no specified type attribute have type equal to submit . 您需要在type="button"上添加type="button"以阻止默认的提交操作,因为没有指定type属性的按钮的类型等于submit The val() method is not applicable to non-form elements, such as spans. val()方法不适用于非形式元素,例如跨度。

You jQuery selector is invalid. 您的jQuery选择器无效。 Use $('.user_name') (it's takes all elements with class 'user_name') instead of $('user_name') . 使用$('.user_name') (它将使用类'user_name'的所有元素)代替$('user_name')

PS: Better give some distinct names or id attributes to those inputs and use corresponding jQuery selector ('#myId' for input with id="myId" or '[name="name1"]' for input with name="name1") PS:最好为这些输入提供一些不同的名称或id属性,并使用相应的jQuery选择器(“ #myId”用于输入id =“ myId”或'[name =“ name1”]]用于输入name =“ name1”)

Here is an example of what you're trying to accomplish. 这是您要完成的示例。

First, I cleaned up your click function a little bit. 首先,我稍微整理了一下点击功能。 I always try to use the shortest method possible to achieve the desired results. 我总是尝试使用最短的方法来达到预期的效果。

Second, you need to us the this keyword inside of the function. 其次,您需要在函数内部使用this关键字。 This gives you access to the button that was actually clicked. 这使您可以访问实际单击的按钮。 From there, you can find the text that you need by traversing up the DOM 1 level ( .parent() ), then find the .text() instead of the val() . 从那里,您可以遍历DOM 1级别( .parent() ),然后找到.text()而不是val() ,从而找到所需的文本。

As a side note, you shouldn't have a <button> element inside of a <span> element. 附带说明一下,您不应在<span>元素内包含<button> <span>元素。

In this example, I'm appending the name to the div just to show that it's working. 在此示例中,我将名称附加到div只是为了表明它正在工作。

 $(document).ready(function(){ $(".btn").click(function() { var myuser = $(this).parent().text().replace("Click ", ""); $("#message_box").append(myuser); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="message_box"> <div> <span class="user_name"><button class="btn">Click</button> John</span>: <span class="user_message">Hello!</span> </div> <div> <span class="user_name"><button class="btn">Click</button> Jeff</span>: <span class="user_message">Hi!</span> </div> <div> <span class="user_name"><button class="btn">Click</button> Jane</span>: <span class="user_message">Whats up?!</span> </div> </div> 

val() is used elements in which we take user Inputs. val()是用于接收用户输入的元素。 What you are looking for is text(); 您正在寻找的是text();

$(document).ready(function(){ $(document).on("click", ".btn" , function() { //if you want to access the attributes of the parent span of button which is clicked, use following code $(this).closest('span').text(); //if yoU want to access the attributes of next span with class user_message, use following code $(this).closest('span').next().text(); }); }); $(document).ready(function(){$(document).on(“ click”,“ .btn”,function(){//如果您想访问被单击按钮的父级跨度的属性,使用以下代码$(this).closest('span')。text(); //如果您要使用user_message类访问下一个span的属性,请使用以下代码$(this).closest('span')。 next()。text();});});

Your span is encapsulating the button which is invalid. 您的跨度封装了无效的按钮。 I have used data attributes of HTML-5 for the same.You can use any of solution which are answered above or go with the data-attributes. 我已经使用了HTML-5的数据属性。您可以使用上面回答的任何解决方案,也可以使用数据属性。

<div id="message_box">
    <div>
        <button class="btn" data-user-name="John">Click</button><span class="user_name"> John</span>: <span class="user_message">Hello!</span>

    </div>
    <div>
        <button class="btn" data-user-name="Jeff">Click</button><span class="user_name"> Jeff</span>: <span class="user_message">Hi!</span>

    </div>
    <div>
        <button class="btn" data-user-name="Jane">Click</button> <span class="user_name">Jane</span>: <span class="user_message">Whats up?!</span>

    </div>
</div>

JavaScript 的JavaScript

$(document).ready(function () {
     $(document).on("click", ".btn", function () {
         var myuser = $(this).data("user-name");
         alert(myuser)
     });
 });

Demo 演示版

<div id="message_box">
  <div>
    <button class="btn">Click</button>
    <span class="user_name"> John</span>:
    <span class="user_message">Hello!</span>
  </div>
  <div>
    <button class="btn">Click</button>
    <span class="user_name">Jeff</span>:
    <span class="user_message">Hi!</span>
  </div>
  <div>
    <button class="btn">Click</button>
    <span class="user_name"> Jane</span>:
    <span class="user_message">Whats up?!</span>
  </div>
</div>


$(document).on("click", ".btn" , function() {
    //var myuser = $('user_name').val();
    var myuser = $(this).parent().find('.user_name').text();
    alert(myuser);
  });

Working example here 这里的工作示例
Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM