【问题标题】:VueJS/jquery get value from P tag with button clickVueJS/jquery 通过单击按钮从 P 标签获取值
【发布时间】:2019-03-20 18:48:56
【问题描述】:

单击按钮时,我需要获取商品价格。这是我目前的代码:

   <div id="shop" class="row" v-cloak>
    {{#each items}}
        <img src="{{img}}">
        <p>{{title}}</p>
        <p class="price">{{price}}</p><br>
        <button class="btn btn-danger" @click="buyItem">Buy</button>
    {{/each}}
   </div>

JS:

    methods: {
        buyItem: function(event){    
            console.log($( event.target ).closest( ".price" ).text());
        }
    }

这会在 console.log 中返回空白行。如何获得 price 值?

编辑

server.js(从这里获取项目):

            res.render('game/index', {
                items
            });

使用小胡子来展示物品:

index.hbs:

      <div id="shop" class="row" v-cloak>
    {{#each items}}
        <img src="{{img}}">
        <p>{{title}}</p>
        <p class="price">{{item.price}}</p><br>
        <button class="btn btn-danger" @click="buyItem">Buy</button>
    {{/each}}
      </div>

【问题讨论】:

  • .closest() 方法查看元素父母。如果你真的想使用 jquery,你应该试试.prev()
  • @ry4nolson 没有 jquery 无法解决这个问题... vue 有选项吗?
  • 你完全可以在没有 jquery 的情况下做到这一点。请看下面我的回答。您将无效语法与不当 Vue 使用结合在一起。

标签: jquery vue.js


【解决方案1】:

您应该在事件处理程序中将价格作为参数传递:

... @click="buyItem(price)" ...

您的 buyItem 将变为:

methods: {
        buyItem: function(price){    
            console.log(price);
        }
    }

【讨论】:

  • 之后怎么办?我在数据中创建了price: null,如果我控制台.log 它我得到null
【解决方案2】:

https://jsfiddle.net/mykwgo8x/1/

   <div id="shop" class="row" v-cloak>
      <!-- use v-for directive, not {{#each items}} -->
      <div v-for="item in items">
          <!-- <img src="{{item.img}}"> -->
          <!-- properties need to be accessed with "item." -->
          <p>{{item.title}}</p>
          <p class="price">{{item.price}}</p><br>
          <button class="btn btn-danger" @click="buyItem(item)">Buy</button>
      </div>
   </div>
new Vue({
  el: "#shop",
  data: {
    items: [
      {
        title: "item 1",
        price : 10
      },
      { 
        title : "item 2",
        price: 2
      }
    ]
  },
  methods: {
    buyItem: function(item){
        console.log(item.price);
    }
  }
})

【讨论】:

  • 啊,我得到了item undefined,因为我没有使用v-for。我应该为每个项目创建一个item 的课程吗?
  • 你真的在使用 Vue 吗? {{#each 不是 Vue 中的循环。使用 v-for 循环遍历 Vue 数据中的项目。
  • 我正在使用 vue。但是要从我的后端 server.js 获取项目,我需要使用 {{#each 来获取它们
  • 这没有任何意义。 {{#each 是小胡子语法。 Vue 不使用它。发布更多代码,也许它会有意义。该模板是否在后端运行?
  • 我更新了。好吧,是的,我应该用什么来代替 NodeJS ?验证?
猜你喜欢
  • 1970-01-01
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
相关资源
最近更新 更多