【问题标题】:Append a child element to another div while having a reference to the orginal parent element在引用原始父元素的同时将子元素附加到另一个 div
【发布时间】:2016-08-03 18:21:32
【问题描述】:

我有这个html 代码

<div id="left-container" class="w3-container w3-left">
    <div class="wordDiv w3-container w3-pale-green w3-leftbar w3-border-green w3-hover-border-red">
        <h1>Give</h1>
        <h3>Selected Definition:</h3>
        <ul style="display:none;">
            <li> offer in good faith </li>
            <li> inflict as a punishment </li>
            <li> afford access to </li> 

        </ul>
    </div>

    <div class="wordDiv w3-container w3-pale-green w3-leftbar w3-border-green w3-hover-border-red">
        <h1>Up</h1>
        <h3>Selected Definition:</h3>

        <ul style="display:none;">
            <li> to a higher intensity </li>
            <li> to a later time </li>
            <li> used up </li>

        </ul>
    </div>

</div>

<div id="right-container" class="w3-container w3-right"></div>

我希望用户在单击其中一个 wordDiv 后能够在正确的容器中看到该词的潜在定义(在每个“wordDiv”的“ul”元素中找到),选择定义之一,然后我想在左侧容器的原始 wordDiv 中显示所选定义。

你可以找到Jsfiddle Demo Here

【问题讨论】:

  • 你需要 javascript 来做到这一点:在点击时在 .wordDiv 上添加一个监听器,然后设置然后选择你想要的 li,获取它的内容并将它添加到你想要的地方
  • 我知道,但我怎样才能回来。我的意思是在我将“ul”附加到右容器后,如何将选定的 li 定义添加到正确的单词 div 中?

标签: javascript jquery html css w3.css


【解决方案1】:

使用 jQuery 的解决方案。 Updated Fiddle

$(function() {
  $('.wordDiv').click(function() {
    var txt = $(this).find('ul').html();
    $('#right-container').html('<ul>' + txt + '</ul>')
  })
})

【讨论】:

  • 我希望用户然后选择其中一个定义,然后将其显示在原始单词 div "Selected Definition" 中。所以基本上 "li" 元素是一个单选输入。跨度>
【解决方案2】:

请查看fiddle

我已根据您选择的 div 将 li 元素添加到另一个 div。

【讨论】:

  • 我希望用户然后选择其中一个定义,然后将其显示为原始单词 div “Selected Definition”.. 所以基本上“li”元素是一个单选输入。跨度>
【解决方案3】:

您可以在 click 函数中使用 jQuery 的 this 变量,这是您的请求的工作 jQuery 示例Updated Fiddle

它将 li 元素放在正确的 div 中并添加 onclick 侦听器,该侦听器具有其来源的知识;)

$('h1').click(function(){
var origin=$(this);
	$(this).siblings('ul').children().click(function(){
		$(this).parent().hide();
		$(origin).parent().append(this);
  	    $(this).replaceWith($('<div>' + this.innerHTML + '</div>'))
})
  
  $(this).siblings('ul').show();
  $("#right-container").append($(this).siblings('ul'));
  
})

$('ldi').click(function(){
	$(this).parent().hide();
	$(this).parent().parent().append(this);
  $(this).replaceWith($('<div>' + this.innerHTML + '</div>'))
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-16
    • 2021-11-27
    • 2015-06-17
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    相关资源
    最近更新 更多