【问题标题】:How select the selector from its method?如何从其方法中选择选择器?
【发布时间】:2014-09-26 14:18:03
【问题描述】:

我需要使用 'this' 更改 '#foo #three' 的文本以获取 div#one 的文本

我需要的输出是:

HTML:

<div id="foo">
 <div id="one">cat</div>
 <div id="two">dog</div>
 <div id="three">mouse</div>
</div>

JS:

$("#foo #three").text($(this).parent().children().first().text());

我需要这个代码动态

http://jsfiddle.net/Kodam/s466a31q/

【问题讨论】:

  • $("#foo #three") 将返回 one 元素。 究竟你想做什么?你想要$("#foo #three").text($('#foo div:first').text());吗? (或者,更好的是:$('#three").text($('#one').text());)无法在另一个选择器中引用之前的选择器。
  • this 的上下文从未改变。你真正想做什么?还有,你为什么选择不止一个id
  • @RocketHazmat OP 说他们想将li#one 复制到li#three;该列表是最终输出。
  • 也许你想要$("#foo #three").text($(this).text());,虽然它完全没有改变......
  • P.S. $('this') 将寻找 &lt;this&gt; 标签。

标签: javascript jquery css


【解决方案1】:

除非您尝试动态执行此操作,否则这很简单:

$('#three').text($('#one').text());

【讨论】:

  • sry,是的,这很有趣
  • 您能演示一下您的动态设置吗?你现在要求的没有任何意义。
  • 我需要将 'mouse' for 'cat' 从 '#foo #three' 更改为他的父级,然后选择其第一个子级的文本。我已经更新了问题。
  • 我试过这个 $("#foo #three").text($(this).parent().children().first().text());但它不起作用
  • 当然不是; this 可能指的是window。你能解释一下为什么你需要这样做吗?您问的是如何实现特定(无意义的)解决方案,而不是提出您想要解决的问题
【解决方案2】:
$("#three").text($('#foo').children().first().text());

更新:如果你真的想用这个来引用匹配,建议使用每个:

$("#foo #three").each(function(){ // this only matches #three
  $(this).text($(this).parent().children().first().text());  
})

【讨论】:

  • 您的答案有效。所以没有办法像这样在方法 text() 中使用 $(this) 吗? $("#foo #three").text($(this).parent().children().first().text());
  • 不,我所知道的最接近的是我发布的内容
【解决方案3】:

虽然这种方法使用了一种变通方法,但它确实有效:

$jSelect = $("#foo #three");
$jSelect.text( function(){
var jParts = $jSelect.selector.split(" ");
  return $(jParts[0]).find("div:first").text();
});

Fiddle

但我不推荐它,因为 .selector 自 jQuery 1.7 起已被弃用,仅在 jQuery Migrate 插件中支持 live()
供参考:http://api.jquery.com/selector/

更新:和类似的方法不使用.selector

jSelect = ("#foo #three");
$(jSelect).text( function(){
 var jParts = jSelect.split(" ");
 return $(jParts[0]).find("div:first").text();
});

Fiddle

【讨论】:

  • 我更新了问题。此外,我不喜欢使用“选择器”。
  • @DocKodam 使用不使用“.selector”的版本更新了答案
【解决方案4】:

如果你坚持使用this,你可以这样:

Fiddle Example

基本上,由于this 仅在函数上下文中起作用,因此您创建一个返回字符串的函数并将其放入.text() 中。

$(function () {
    $("#foo #three").text(function () {
        return $(this).parent().children().first().text();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
    <div id="one">cat</div>
    <div id="two">dog</div>
    <div id="three">mouse</div>
</div>

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    相关资源
    最近更新 更多