jQuery用换行符替换<p>标签

时间:2015-11-28 09:31:06

标签: javascript jquery html

我有一个像这样的html文本:

<div>
    <p>1111</p>
    <p>2222</p>
    <p>3333</p>
</div>

我想将<p>标记替换为换行符,但将所有文本转换为<p>标记:

<div>
    <p>
        1111
        <br/>
        2222
        <br/>
        3333
        <br/>
    </p>
</div>

我尝试使用replaceWith,但结果与我想要的结果不同

4 个答案:

答案 0 :(得分:3)

这对你有用吗?

$("div > p").each(function () {
    $(this).replaceWith($(this).text() + "<br/>");
});
$("div").wrapInner("<p></p>");

https://jsfiddle.net/vnLnmx0c/

答案 1 :(得分:2)

你可以这样做:

@Component("authenticationProvider")
public class LoginAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    UserDAO userDAO;

    @Autowired
    @Qualifier("userDetailsService")
    @Override
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        super.setUserDetailsService(userDetailsService);
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        try {
            Authentication auth = super.authenticate(authentication);
            // if reach here, means login success, else exception will be thrown

            // reset the user attempts
            userDAO.resetPasswordRetryAttempts(authentication.getName());

            return auth;
        } catch (BadCredentialsException ex) {
            // invalid login, update user attempts
            userDAO.updatePasswordRetryAttempts(authentication.getName(), PropertyUtils.getLoginAttemptsLimit());
            throw ex;
        } catch (LockedException ex) {
            // this user is locked
            throw ex;
        } catch (AccountExpiredException ex) {
            // this user is expired
            throw ex;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }

}

工作代码here

答案 2 :(得分:1)

这是一个仅使用javascript的可能解决方案。

&#13;
&#13;
element = document.getElementById("replace"); //Replace for whatever you want
html = element.innerHTML;
html = html.replace(/<p>(.*)<\/p>/g, "$1<br />"); //$1 here contains all the html between the <p> tags. So you can change this around to what you want it to be, example: <a>$1</a>
element.innerHTML = html;
&#13;
<div id="replace">
  <p>1111</p>
  <p>2222</p>
  <p>3333</p>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我为你创造了一个小提琴。检查

https://jsbin.com/gazefa/edit?html,js,output

<button onclick="removePs('target')">Remove Multiple Ps</button>
<div id="target">
    <p>1111</p>
    <p>2222</p>
    <p>3333</p>
</div>

JS

function removePs(div_id) {
  var html = '<p>';
  $('#' + div_id + ' p').each(function(i, p) {
    html += $(p).html() + '</br>';
  });
  html += '</p>';
  $('#' + div_id).html(html);
}