拆分href并将html放入变量中

时间:2018-01-05 19:41:26

标签: javascript jquery variables split href

我想发送此HTML,减去" / modal"变成一个变量:

<span class="detailsLink"><object><a href="/content/modal/30OffLucky" class="js-modal btn-secondary">DETAILS</a></object></span>

如何添加到此行以使其正常工作?:

var eemailDetails = $('.detailsLink').html();

这会在将/ modal传递给变量之前取出/ modal:

var eemailDetails = $('.detailsLink a').each(function(){
    this.href = this.href.replace('/modal', '');
}).html();

感谢您的时间!

2 个答案:

答案 0 :(得分:1)

应该对检索到的值而不是元素的属性进行替换。

因此,要检索包含目标元素的HTML标记,可以使用outerHTML property

// Get the whole HTML
var eemailDetails = $('.detailsLink')[0].outerHTML;

// Remove /modal
eemailDetails = eemailDetails.replace('/modal', '');


console.log("The attribute unchanged: "+$('.detailsLink a').attr("href"));
console.log("The HTML retrieved: "+eemailDetails);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="detailsLink"><object><a href="/content/modal/30OffLucky" class="js-modal btn-secondary">DETAILS</a></object></span>

答案 1 :(得分:1)

因此每个工作正常,我将变量保存为元素本身的数据属性。稍后,当它被点击时,我可以根据需要调用该数据属性。希望这有帮助!

&#13;
&#13;
$('.detailsLink a').each(function(){
  var changedLink = this.href.replace('/modal', '');
    $(this).data("changedLink", changedLink)
});

$(".detailsLink a").on("click", function(event){
  event.preventDefault();
  var returnEl = $(this).parents(".detailsLink").clone();
  returnEl.find("a").attr("href", $(this).data("changedLink") );
  
  console.log(returnEl[0].outerHTML );
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="detailsLink"><object><a href="/content/modal/30OffLucky" class="js-modal btn-secondary">DETAILS</a></object></span>
<span class="detailsLink"><object><a href="/content/modal/30OffNotSoLucky" class="js-modal btn-secondary">More DETAILS</a></object></span>
<span class="detailsLink"><object><a href="/content/modal/HaveAFrog" class="js-modal btn-secondary">Yet More DETAILS!</a></object></span>
&#13;
&#13;
&#13;