如何在jQuery中使用特定值定位特定属性? [英] How to target specific attribute with a certain value in jQuery?

查看:154
本文介绍了如何在jQuery中使用特定值定位特定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要解决的问题是:

编写函数newMessage,该函数接收主题名称作为参数.如果data-topic-name为topicName,则函数应将p标签的背景颜色更改为红色.

Write the function newMessage, which receives the name of the topic as the parameter. Function should change the background-color of the p tag to red where the data-topic-name is topicName.

例如,如果HTML是:

For example, if the HTML is:

<div>
  <p data-topic-name="discussion">General discussion</p>
  <p data-topic-name="bugs">Bugs</p>
  <p data-topic-name="animals">Animals</p>
</div>

在调用newMessage("discussion")之后,HTML应该是:

After calling newMessage("discussion") the HTML should be:

<div>
  <p data-topic-name="discussion" style="background-color: red;">General discussion</p>
  <p data-topic-name="bugs">Bugs</p>
  <p data-topic-name="animals">Animals</p>
</div>

现在,当我使用以下代码时,我以为自己拥有了它:

Now, I thought I had it when I used the following:

function newMessage(topicName) {
  $('p[data-topic-name=topicName]').css('background-color' , 'red')
}

不幸的是,它不起作用.

unfortunately it does not work.

我认为p[data-topic-name = topicName]是使用的正确选择器?

I thought p[data-topic-name = topicName] was the correct selector to use?

推荐答案

您处在正确的轨道上,但需要将变量名移到引号之外,例如:

You're on the right track but you need to move the variable name outside of your quotes like:

function newMessage(topicName) {
  $('p[data-topic-name='+topicName+']').css('background-color' , 'red')
}

示例:

function newMessage(topicName) {
  $('p[data-topic-name='+topicName+']').css('background-color' , 'red')
}
newMessage('discussion');

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p data-topic-name="discussion">General discussion</p>
  <p data-topic-name="bugs">Bugs</p>
  <p data-topic-name="animals">Animals</p>
</div>

这篇关于如何在jQuery中使用特定值定位特定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆